Typescript 打字脚本+;ES6地图+;对象类型的索引签名隐式具有';任何';类型

Typescript 打字脚本+;ES6地图+;对象类型的索引签名隐式具有';任何';类型,typescript,ecmascript-6,es6-shim,Typescript,Ecmascript 6,Es6 Shim,我在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. } }

我在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.
    }
}
导出类配置
{
私有选项=新映射();
构造函数(){
}
public getOption(名称:string):string{
返回此。选项[名称];//
但是es6没有静态类型,对吗?那么,为什么映射需要键/值类型作为泛型参数呢

这些是编译时类型。与键入数组的方式类似:

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

从ES6映射对象检索键是通过使用数组操作符的、not来完成的


因为JavaScript中的所有对象都是动态的,并且可以添加属性,所以仍然可以对映射对象使用数组访问操作符,但实际上没有使用映射功能是错误的,您只是向实例添加了任意属性。您也可以使用
{}
而不是
new Map()
。TypeScript编译器试图通过警告您试图使用不存在的索引签名来告诉您这一点。

尝试为选项创建接口。例如

interface IOptions {

[propName: string]: string;

}

这个答案是不正确的。Map没有指定索引签名的返回类型“为了安全”,它根本没有指定索引签名,因为Map对象不是这样工作的(它们有get/set方法)。TL;DR:使用
Map.get(key)
而不是
Map[key]
interface IOptions {

[propName: string]: string;

}