Meros
Meros

Reputation: 1358

Unexpected behaviour of TypeScript array

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;

http://www.typescriptlang.org/Playground#src=var%20test%3A%20string%5B%5D%20%3D%20%5B%5D%3B%0A%2F%2F%20OK%20as%20expected%0Atest%5B1%5D%20%3D%20%2242%22%3B%0A%0A%2F%2F%20Error%20as%20expected%0Atest%5B1%5D%20%3D%2042%3B%0A%0A%2F%2F%20Error%20as%20expected%0Atest.test%20%3D%2042%3B%0A%0A%2F%2F%20Unexpected%20OK%2C%20why%3F%20%0Atest%5B'1'%5D%20%3D%2042%3B%0A%0A

Does anyone know why it is like this?

Upvotes: 1

Views: 131

Answers (2)

basarat
basarat

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

Pavel Patrin
Pavel Patrin

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

Related Questions