TS7017: Index signature of object type implicitly has an 'any' type.

Topics: General
Feb 4, 2014 at 2:53 AM
Edited Feb 4, 2014 at 3:01 AM
On current develop branch there seems to be a new implicit checking that, when running with --noImplicitAny, is doing some sort of checking that I can’t make sense of.

Given this function:
function applyMixins(derivedCtor:any, baseCtors:any[]):void {
    for (var i = 0, baseCtor:Function; (baseCtor = baseCtors[i]); ++i) {
        var prototype = baseCtor.prototype;
        for (var k in prototype) {
            if (prototype[k] !== Object.prototype[k]) { // error TS7017
                derivedCtor.prototype[k] = prototype[k];
            }
        }
    }
}
This warning goes away if I merge the Object interface to add back an explicit indexer:
interface Object {
  [key:string]:any;
}
or, alternatively, if I coerce Object.prototype as { [key:string]: any; } on that line.

I don’t understand what is an implicit any in the above code that I should be told about. Object.prototype keys? Well, what in the world am I supposed to do consistently about that, except add back the index signature that was removed in 0.9.5?

Thanks,
Coordinator
Feb 5, 2014 at 10:06 PM
Any time you reference an object with an indexer that the compiler can't be sure exists, you'll get an implicit any warning.

For example:

var x = {};
x["magic string"]; 

The goal of the no implicit any is to help catch situations where you've accidentally typed something, or you're using objects in a way that may return undefined members and the compiler can't be sure the member exists first. Or, more generally, any time the compiler has to infer that the result is 'any' because it can't be sure of the type.

In the above, we can't be sure that k is something in the prototype because we only check the type of the access locally, not as part of a larger context. Here that means that 'Object.prototype[k]' would give the warning.

You've got the right idea with the work-around. If you want to use object more liberally, you can give an explicit indexer, so that the type that comes out is an explicit any (rather than an implicit any).