The distinction between any and any[] lies in the realm of Intellisense.
var a:any = .....
a.map , a.join (no intellisense, typescript is unaware if 'a' is an array or not)
var a:any[] = ....
a.map , a.join (typescript recognizes 'a' as an array and provides intellisence)
Errors at Compilation Time
var aa:any[] = "a"; // Error - TypeScript will not permit this
var a:any = "a"; // 'a' can be a string, no harm done here
aa = a; // Error cannot be detected by TypeScript
// at compile time because 'a' can be an array
var someString:string;
aa = someString; // TypeScript knows that 'aa' is an array and 'someString' is not
When you declare something as any[]
, you are specifying that you desire this object to be of type an array. However, 'any' can literally be anything, including an array so TypeScript allows assigning 'any' to any array.
TypeScript is capable of identifying compile-time errors whenever possible, but when you designate something as any, it won't anticipate compile-time errors.
It is at the discretion of the compiler designer whether to enforce such compile-time errors or not. I believe the following scenario should not be permitted,
a:any
aa:any[] = a; // this should trigger a compile-time error
To prevent this, one can certainly cast it as aa = a as any[]
, similar to practices in languages like C# and Java.
Runtime Errors
JavaScript lacks type specifications for variable declaration, hence the JavaScript engine is uninformed about types.
Only when a method is invoked or a property is accessed, JavaScript will throw an error.
a:any[] ..
// TypeError: .map is not a function will be thrown
a.map( ()=> ... )
a.length // This will be undefined.. any member of any object is essentially undefined, there is no type error during access