如何在TypeScript中正确更改变量的类型?

rya*_*ain 10 typescript typescript1.5 angular

感谢您的耐心等待,我刚开始使用TypeScript.

我正在开发一个角度2的应用程序,需要接受文本输入,然后进行一堆计算.我(错误地?)假设我需要首先将输入绑定到我的数据模型中的"任何"类型变量,然后将这些变量转换为数字以便处理数字.我环顾四周,无法找到如何做到这一点,它不会抛出这个TS编译器错误:

`src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.`
Run Code Online (Sandbox Code Playgroud)

在我的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;
}
Run Code Online (Sandbox Code Playgroud)

和ModelFields定义(谢谢tarh!)

export class ModelFields { 
    constructor( 
        public fieldName: any, 
        public anotherField: any 
    ) 
    {} 
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢大家!

jos*_*las 11

你无法在TypeScript中更改变量的类型,这只是为了制作相反的TS.相反,您可以将变量声明为"any",这相当于JS中的经典"var"变量,无类型.

声明变量后,您将无法重新键入它.但是,您可以做的是声明"any",然后在您想要使用它时将其强制转换,以便将其用作所需类型.

例如,这不会引发任何错误:

let a: any;

a = 1234;
(a as number).toExponential();

a = "abcd"; 
(a as string).substr(1, 4);
Run Code Online (Sandbox Code Playgroud)

对于您的类,这也是正确的,没有类型错误:

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
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,您应该使用“未知”而不是“任何”。除非绝对必要,否则应避免使用“任何”。 (3认同)