“any” in Typescript

后端 未结 4 1564
不知归路
不知归路 2021-01-20 15:10

I am beginner in typescript. I have a doubt in usage of \"any\" type.

Using \"any\" is basically opting out type checking if I am right. For example

相关标签:
4条回答
  • 2021-01-20 15:48

    First of all - If we speak about Typescript, lets avoid the var key-word.

    We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:

    Example to this:

    let notSure: any = 4;
    notSure = "maybe a string instead";
    notSure = false; // okay, definitely a boolean
    

    More: Types in Typescript

    0 讨论(0)
  • 2021-01-20 15:54

    While the two are equivalent in use (because any is the default type when unspecified) by explicitly specifying the type as any, you explicitly declare the intent.

    Intellisense, where available, will display the type as any, allowing easier understanding how your variable is meant to be used.

    0 讨论(0)
  • 2021-01-20 16:07

    Any: any type. Used when impossible to know the type. When you declare type as any, you can reassign any type of value in that variable.

    var num:any = 12;
    num = boolean;
    num = "abcd"
    
    0 讨论(0)
  • 2021-01-20 16:08

    any opts out type checking as you have said. The second description you have came up with (without any) will compile too. But it is not valid(*) when you use linting like tslint.

    (*) By not valid, I meant the IDE you use will pop up an alert. But, to the bottom line; any valid Javascript code is also valid for Typescript on the grounds of compiling.

    0 讨论(0)
提交回复
热议问题