TypeScript + ES6 Map + 对象类型的索引签名隐式具有 'any' 类型

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

我在 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.
    }
}

编译器给我这个错误:

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

地图是 'possible' 通过 es6-shim。我不太确定这里发生了什么。实际上这张地图让我有点困惑。 Map 应该来自 es6-shim,它应该实现 es6 功能。但是 es6 没有静态类型,对吧?那么,为什么 Map 期望 key/value 类型作为通用参数?我看到有些人添加了 'noImplicitAny' 标志,但我想解决问题,而不是忽略它。

谢谢。

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

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

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

这两行都编译为 new Array() 但其中一行确保检查成员

This line causes the error.

因为 Mapdefinition 没有指定索引签名的 return 类型类型安全。

快速修复:

public getOption(name: string): string {
    return this.options[name] as string;
}

通过 Map.prototype.get methodnot 使用数组运算符从 ES6 Map 对象检索键。

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

尝试为选项创建界面。像,

interface IOptions {

[propName: string]: string;

}