How to properly change a variable's type in TypeScript?

前端 未结 3 447
天涯浪人
天涯浪人 2021-02-07 07:59

Thanks for your patience here, I\'m just starting out with TypeScript.

I\'m working on an angular 2 app that needs to accept text inputs and then make a bunch of calcul

3条回答
  •  不知归路
    2021-02-07 08:47

    You cannot change a variable's type in TypeScript, that's just the opposite TS was made for. Instead, you can declare a variable as "any", which would be equivalent to a classic "var" variable in JS, untyped.

    Once a variable is declared, you will not be able to retype it. What you could do, however, is to declare "any" and then cast it whenever you want to use it, in order to use it as the desired type.

    For example this would not throw any errors:

    let a: any;
    
    a = 1234;
    (a as number).toExponential();
    
    a = "abcd"; 
    (a as string).substr(1, 4);
    

    In case of your class, this would be also correct, no type errors:

    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
    

提交回复
热议问题