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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With