最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using strong typed Map - Stack Overflow

programmeradmin1浏览0评论

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;
}

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();

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?

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;
}

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();

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?

Share Improve this question edited Feb 8, 2023 at 17:52 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Jun 18, 2016 at 7:36 BeetleJuiceBeetleJuice 40.9k21 gold badges118 silver badges180 bronze badges 2
  • I think it's better to define an interface for {name:string,price:number} – alexeibs Commented Jun 18, 2016 at 8:54
  • Typically i would do so. It wouldn't have helped me here: the error was triggered because there was no type on the right sign of the assignment (next to new Map). – BeetleJuice Commented Jun 18, 2016 at 20:47
Add a comment  | 

1 Answer 1

Reset to default 19

You need to provide generic types information to the created Map like this:

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

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

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

评论列表(0)

  1. 暂无评论