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

3

19

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.

Geronto answered 4/1, 2016 at 4:12 Comment(0)
D
23

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.

Densmore answered 4/1, 2016 at 14:55 Comment(1)
TL;DR: Use map.get(key) instead of map[key].Enfranchise
S
1

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;
}
Spool answered 4/1, 2016 at 4:27 Comment(1)
This answer is not correct. Map doesn’t not specify a return type of an index signature “to be safe”, it specifies no index signature at all because Map objects don’t work that way (they have get/set methods instead).Densmore
M
-1

Try creating interface for options. Something Like,

interface IOptions {

[propName: string]: string;

}
Marable answered 30/9, 2016 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.