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

前端 未结 3 444
天涯浪人
天涯浪人 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:39

    You example is not clear enough, but I guess that your problem is because of Typescript inference:

    var x = 3; // x is a number
    x = "45";  // compiler error
    

    But, if you do:

    var x : any = 3; // x can be anything
    x = "45";
    

    Or:

    var x; // x is any forever
    x = '45';  // x is still any
    

    You can find further details on those great slides and on docs

    Hope this can help a bit...

    0 讨论(0)
  • 2021-02-07 08:46

    Faced a similar type of query and worked for me.

    My case:

    article Id comes in the string format from route params and from API I get the data in number format.

    If I check with !=, ES lint throws an error. So I am converting a string to number in vanilla javascript using Number() method.

    const articleId = Number(this.route.snapshot.params['articleId']);
    
    data.forEach((element, index) => {
    
        // console.log(typeof(element['id']), element['id']); 
        // 4, number
        // console.log(typeof(this.route.snapshot.params['articleId']), this.route.snapshot.params['articleId']);
        // 4, string (converted to number)
    
        if (element['id'] !== articleId) {
            //my implementation
         }
    }
    

    Reference Link:

    1. https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题