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
Using strong typed Map
提问by BeetleJuice
I'm having trouble strong typing my Map
objects with typescript 1.8.10
. Here is an excerpt from core-js
defining the Map interface:
我在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;
}
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 Map
objects 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 Map
like 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}>();