Ido Ran
Ido Ran

Reputation: 11384

Why TypeScript allow convert from string to number without warning

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

Upvotes: 8

Views: 4394

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221044

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
}

Upvotes: 18

Related Questions