感谢您的耐心等待,我才刚刚开始使用 TypeScript。
我正在开发一个需要接受文本输入然后进行大量计算的 Angular 2 应用程序。我(错误地?)假设我需要首先将输入绑定(bind)到我的数据模型中的“任何”类型变量,然后将这些变量转换为数字以处理数字。我环顾四周,找不到如何以不引发此 TS 编译器错误的方式执行此操作:
`src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.`
在我的 CalculatorService 中,我有这个功能:
/*
* Convert the object of strings recieved from the form into a clean object of integers
*/
n(model:ModelFields) {
// Clone it
this.numericModel = Object.assign({}, this.model);
for (var prop in this.numericModel) {
if (this.numericModel.hasOwnProperty(prop)) {
// strip off all non-numeric charactersklj
this.numericModel[prop] = this.numericModel[prop].replace(/\D/g,'');
// convert to Any typescript type
// this breaks the application, and still throws a compiler error. nope.
// this.numericModel[prop] = this.numericModel[prop]:Any;
// convert to Number type
// this gives a typescript console error, but seems to still compile...
// ignoring this for now in order to meet deadline
this.numericModel[prop] = +this.numericModel[prop];
}
}
return this.numericModel;
}
和 ModelFields 定义(感谢 tarh!)
export class ModelFields {
constructor(
public fieldName: any,
public anotherField: any
)
{}
}
有什么想法吗?谢谢大家!
最佳答案
您不能在 TypeScript 中更改变量的类型,这恰恰与 TS 的目的相反。相反,您可以将变量声明为“any”,这相当于 JS 中的经典“var”变量,无类型。
一旦声明了变量,您将无法重新键入它。但是,您可以做的是声明“any”,然后在您想要使用它时转换它,以便将其用作所需的类型。
例如这不会抛出任何错误:
let a: any;
a = 1234;
(a as number).toExponential();
a = "abcd";
(a as string).substr(1, 4);
对于您的类(class),这也是正确的,没有类型错误:
class ModelFields {
constructor(
public fieldName: any,
public anotherField: any
)
//...
}
let model: ModelFields = new ModelFields(1, 2);
console.log(model.fieldName + model.anotherField); // --> 3
model.fieldName = "a";
model.anotherField = "b";
console.log(model.fieldName + model.anotherField); // --> ab
关于typescript - 如何在 TypeScript 中正确更改变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33615680/