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