Implicit any and index signatures

Topics: General
Feb 26, 2014 at 12:15 PM
Hi,

as of 1.0RC indexing into an object using bracket notation generates an error, when compiled with "noimplicitany":
var foo = {};
foo["bar"] = 10; // Index signature of object type implicitly has an 'any' type
This has turned out to be a massive breaking change for us, especially within the test and mock frameworks where a lot of dynamic access and other magic occurs.

The workaround is rather verbose:
var foo: { [index:string]: any } = {};
foo["bar"] = 10;

// Or
var foo = {};
(<any>foo).bar = 10; 
In the past when there's been a new release, and I eagerly run it over my code-base, and the compiler spots a hidden bug, I've always said to myself "crumbs! well done, you typescript chappies!" But unfortunately there was no such sentiment for this particular gem.

Why make something as fundamental to JavaScript as foo["bar"] an error?

This may be mathematically 100% correct, but in practice it's a massive nuisance, and has not helped to trap a single bug.

Please tell me this is a bug - not a feature.
Coordinator
Feb 26, 2014 at 3:49 PM
We had actually intended to warn on accessing objects like that without an explicit indexer, but the compiler hadn't been catching it until recently. There's an easy work around to get to the old behavior. Rather than fixing every single index operation, you can use an interface merge and give an explicit 'any' indexer to all of the objects at once:
interface Object {
    [idx: string]: any;
}
Marked as answer by nabog on 2/27/2014 at 1:57 AM
Jul 23, 2014 at 4:28 PM
Edited Jul 23, 2014 at 4:29 PM
Is it the type of the object that's the problem or the type of the property? I find the error message a little unclear.

It's my understanding that when iterating over a standard Javascript object with a for loop the index is always a string(even for Arrays). Am I wrong?
var obj = {foo: "bar"};
for (var key in obj) {
    var value = obj[key]; // throws "error TS7017: Build: Index signature of object type implicitly has an 'any' type."
}