What is the difference between any and any[ ]?

后端 未结 4 2209
旧时难觅i
旧时难觅i 2021-02-19 13:34

What is the difference between any and any[ ]?


Example 1 (working as expected)

name1: any;
name2: any[];
this.name1 = this.name2;
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 14:09

    Difference between any and any[] is in Intellisence.

    var a:any = .....
    
    a.map , a.join (no intellisense, typescript does not know if a is an array or not)
    
    
    var a:any[] = ....
    a.map , a.join (typescript knows that a is an array and will provide intellisence)
    

    Compile time errors

    var aa:any[] = "a"; // error typescript will not allow this
    
    var a:any = "a"; // a can be string, there is no harm
    
    aa = a; // typescript cannot detect error at 
            // compile time because a can be array
    
    var someString:string;
    
    aa = someString; // typescript knows that aa is an array and someString is not
    

    By declaring something any[], you are telling that I want this object to be of type an array. However, any is literally anything, even array can be any so typescript allows you to assign any to any array.

    TypeScript will detect compile time errors whenever it could, but when you set something to any, it will not detect compile time errors.

    It is upto compiler designer to enforce such compile time error or not, I guess following should not be allowed,

     a:any 
     aa:any[] = a; // this should be compile time error
    

    To avoid, one can certainly cast it as aa = a as any[], same as in languages like C# and Java.

    Runtime error

    JavaScript has no type specification for declaration of variable, so JavaScript engine does not have any idea of about type.

    Only when you invoke a method or access property, JavaScrip will give you an error..

    a:any[] ..
    
    // this will give an error TypeError: .map is not a function
    a.map( ()=> ... )
    
    a.length // this is undefined.. any member of any object is
    // essentially undefined, there is no type error when you access
    // member
    

提交回复
热议问题