Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why TypeScript allow convert from string to number without warning

Tags:

typescript

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())
}
like image 773
Ido Ran Avatar asked Oct 18 '12 18:10

Ido Ran


1 Answers

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
}
like image 60
Ryan Cavanaugh Avatar answered Nov 04 '22 15:11

Ryan Cavanaugh