TypeScript Map:如何使用强类型?

Bee*_*ice 12 javascript typescript ecmascript-6

我很难用键入我的Map对象typescript 1.8.10.以下是core-js定义Map接口的摘录:

interface Map<K, V> {
    clear(): void;
    delete(key: K): boolean;
    forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
    get(key: K): V;
    has(key: K): boolean;
    set(key: K, value?: V): Map<K, V>;
    size: number;
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个使用字符串键的地图,并且只存储具有该形状的值{name:string,price:number}.我尝试用以下方式声明我的对象:

let oMap:Map<string,{name:string,price:number}> = new Map();
Run Code Online (Sandbox Code Playgroud)

但是,编译器会抛出错误TS2322: Type 'Map<{}, {}>' is not assignable to type 'Map<string, { name: string; price: number; }>'.Map在打字稿中使用ES6 对象时,有没有办法利用强类型?

zlu*_*mer 16

您需要为创建的提供泛型类型信息Map:

let oMap:Map<string,{name:string,price:number}> = new Map<string,{name:string,price:number}>();
Run Code Online (Sandbox Code Playgroud)

之后,您可以省略类型声明,将作业留给编译器:

// oMap is correctly inferred to be Map<string,{name:string,price:number}>
let oMap = new Map<string,{name:string,price:number}>();
Run Code Online (Sandbox Code Playgroud)