What is the difference between any and any[ ]?

Viewed 2742

What is the difference between any and any[ ]?


Example 1 (working as expected)

name1: any;
name2: any[];
this.name1 = this.name2;

Example 2 (This is also working as expected)

name1: any;
name2: any[];
this.name2 = this.name1;

Why typescript allowing any data type can be access any[] data type. As same as any[] data type can be access any type of data? and Which one is best to use? And If the data type is just an object (not an array) like string or number or object or any, then why any[ ] will be accept that object type without showing any run-time or compile-time error?.


4 Answers

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
  1. only Any used for single object of any type.
  2. Any[] is for array of objects with type Any.
Related