谢谢你的耐心,我刚开始打字。
我正在开发一个Angular2应用程序,它需要接受文本输入,然后进行一系列计算。我(不正确?)假设我需要首先将输入绑定到数据模型中的“任意”类型变量,然后将这些变量转换为数字,以便处理数字。我环顾四周,找不到这样做的方法,它不会抛出这个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 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/