使用强类型地图 [英] Using strong typed Map
问题描述
我很难用typescript 1.8.10
键入Map
对象.以下是core-js
定义Map接口的摘录:
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:
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;
}
我想创建一个使用字符串键的映射,并且只存储形状为{name:string,price: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:
let oMap:Map<string,{name:string,price:number}> = new Map();
但是,编译器会引发错误TS2322: Type 'Map<{}, {}>' is not assignable to type 'Map<string, { name: string; price: number; }>'
.在打字稿中使用ES6 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?
推荐答案
您需要像这样向创建的Map
提供通用类型信息:
You need to provide generic types information to the created Map
like that:
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}>();
这篇关于使用强类型地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!