Reputation: 1358
Given a typescript array, I would expect it to limit my options to only adding elements of the value type with an integer index. But this is not really the case and I cannot find a good reason why.
var test: string[] = [];
// OK as expected
test[1] = "42";
// Error as expected
test[1] = 42;
// Error as expected
test.test = 42;
// Unexpected OK, why?
test['1'] = 42;
Does anyone know why it is like this?
Upvotes: 1
Views: 131
Reputation: 276255
This is because of the way the TypeScript is designed. You are allowed to access any object by string indexers and by default it assumes the type any
. This is for convinience of porting over existing code.
For stuff that is defined a string indexing leads to valid type checking, consider:
var test: string[] = [];
// Ok
test['push']('123');
// Error
test['push'](123);
Upvotes: 2
Reputation: 1736
Because at JavaScript:
var a = [];
a[1] = 123;
a['1'] = 456;
alert(a[1]); // 456
Update 1.
Possibly TypeScript compiler could not trace that at square brackets there are not a integer (because of only compile-time checks and no runtime overhead)?
For example, how to check a situation at a compile time?
var idx = getSomething();
var arr: string[] = [];
arr[idx] = 'Abcdef';
Update 2.
First, square brackets is not only used for accessing array items, so it is possible to has a attribute with such name.
Second, there is possible a difficult situation to trace.
Example.
var idx = {}
idx.toString = (): number => { return 2; };
var arr:number[] = [10, 11, 12, 13];
alert(arr[idx]); // 12
It is dynamically correct, but statically... Yes or no?
So, i dont have an answer to your question, but i think that it is just a difficult situation for compiler and it just pass here.
Upvotes: -1