8

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())
}
0

1 Answer 1

18

Short answer: a[i] is of type any, not string.

Long answer: a is of type string[]. In TypeScript, objects of type T[] that are indexed by a number result in a value of type T, but indexing them by a string results in an any. Values of type any can 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:

// Elsewhere...
Array.prototype.danger = 35;

// Meanwhile, back at the ranch:
var a = [ 'z' ];

var i: string;
for (i in a) {
    var x = a[i]; // i = 'danger', a[i] = 35...
}

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:

var a: {[s: string]: string; } = {};
a['hello'] = 'world';
var i:string;
for (i in a) {
    var c : number = a[i]; // Issues an error
}
Sign up to request clarification or add additional context in comments.

1 Comment

Don't use "for ... in" construction that way. Ecma "for... in" is not the same as foreach in c#. You would have to check at each iteration if it is inherited property(like from prototype) or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.