When writing this TypeScript code I was surprised to see that TypeScript compiler does not warn me when I convert from string to number.
var a = new string[];
a.push('a')
a.push('b')
a.push('c')
var i:string;
for (i in a) {
var c : number = a[i]; <---- Here a is string[] but I assign it to c which is number
alert(c.toString())
}
Short answer:
a[i]is of typeany, notstring.Long answer:
ais of typestring[]. In TypeScript, objects of typeT[]that are indexed by anumberresult in a value of typeT, but indexing them by astringresults in anany. Values of typeanycan be freely converted to any other type.Why?
When you index an array by a string, the compiler simply has no ability to predict what’s going to happen, and you’re stuck with
any. Consider:If you’re really confident that no one is going to be mucking with your object, or you’re taking indexes from a known-safe set of string values, you can write an indexing type. In the case where you’re indexing by a string, you’re probably better off using an object rather than an array: