Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript + ES6 Map + Index signature of object type implicitly has an 'any' type

I have the following code in TypeScript:

export class Config
{
    private options = new Map<string, string>();

    constructor() {
    }

    public getOption(name: string): string {
        return this.options[name]; // <-- This line causes the error.
    }
}

And the compiler is giving me this error:

Error:(10, 16) TS7017: Index signature of object type implicitly has an 'any' type.

The Map is 'possible' through es6-shim. I am not quite sure what is going on here. Actually this Map confuses me a little. Map is supposed to come from es6-shim which is supposed to implement es6 functionality. But es6 doesn't have static types, right? So, why the Map expects the key/value types as generic arguments? I have seen some people adding a 'noImplicitAny' flag but I want to solve the problem, not ignore it.

Thank you.

like image 745
AstrOne Avatar asked Jan 04 '16 04:01

AstrOne


2 Answers

Retrieving keys from an ES6 Map object is done through the Map.prototype.get method, not using the array operator.

Because all objects in JavaScript are dynamic and can have properties added to them, it is still possible to use the array access operator with a Map object, but it’s wrong—you’re not actually using the Map functionality, you’re just adding arbitrary properties to the instance. You may as well be using {} instead of new Map() at that point. The TypeScript compiler is trying to tell you so, by warning you that you’re trying to use an index signature that does not exist.

like image 66
C Snover Avatar answered Nov 01 '22 17:11

C Snover


But es6 doesn't have static types, right? So, why the Map expects the key/value types as generic arguments

These are compile time types. Similar how one can type an array:

let foo = new Array(); // array of any 
let bar = new Array<string>(); // array of strings

foo.push(123); // okay
bar.push(123); // Error : not a string

Both lines compile to new Array() but one ensures checking on the members

This line causes the error.

Because the definition for Map doesn't specify the return type of the index signature to be type safe.

Quick Fix:

public getOption(name: string): string {
    return this.options[name] as string;
}
like image 29
basarat Avatar answered Nov 01 '22 16:11

basarat