首页 > 解决方案 > 当我的键是某种接口类型时,Typescript map.get 方法返回未定义

问题描述

我有一个 main.ts 文件,其中有一个映射,键作为接口dr,值作为字符串。当我尝试使用它从地图中获取一些值时,get它返回 undefined 。下面是我的代码:

interface dr {
a: string;
b: string;
}

let myMap = new Map<dr,string>();
myMap.set({ a: 'foo', b: 'bar' }, `this is my map`);

export default (a:string,b:string): string => {
return myMap.get({ a: a, b: b })!;

};

标签: typescriptdictionary

解决方案


对象相等与原始值不同,因为对象不是使用它们的属性值进行比较,而是如果它们具有相同的引用。

let myMap = new Map<dr,string>();
myMap.set({ a: 'foo', b: 'bar' }, `this is my map`); 

您在此处设置{ a: 'foo', b: 'bar' }地图,但您不会将参考存储在任何地方,因此您将永远无法get从地图中取回它。

相反,您必须这样做:

var a = { a: 'foo', b: 'bar' };
myMap.set(a, `this is my map`);
myMap.get(a) // returns 'this is my map' 

或者,您可以“字符串化”您的对象,因此不是将值与对象一起存储为键,而是将它们与字符串一起存储:

var a = { a: 'foo', b: 'bar' };
myMap.set(`${a.a}${a.b}`, `this is my map`);
myMap.get('foobar') // returns 'this is my map'

推荐阅读