Javascript 使用强类型 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37894517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:51:29  来源:igfitidea点击:

Using strong typed Map

javascripttypescriptecmascript-6

提问by BeetleJuice

I'm having trouble strong typing my Mapobjects with typescript 1.8.10. Here is an excerpt from core-jsdefining the Map interface:

我在Maptypescript 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;
}

I want to create a map that uses string keys and only ever stores values with the shape {name:string,price:number}. I tried declaring my object with:

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

let oMap:Map<string,{name:string,price:number}> = new Map();

However, the compiler throws error TS2322: Type 'Map<{}, {}>' is not assignable to type 'Map<string, { name: string; price: number; }>'. Is there a way to take advantage of strong typing when using ES6 Mapobjects in typescript?

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

回答by zlumer

You need to provide generic types information to the created Maplike that:

您需要向创建的对象提供泛型类型信息,Map如下所示:

let oMap:Map<string,{name:string,price:number}> = new Map<string,{name:string,price:number}>();

And after that you can omit type declaration, leaving the job to compiler:

之后你可以省略类型声明,把工作留给编译器:

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