typescript - 当我的键是某种接口类型时,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 })!;
};
解决方案
对象相等与原始值不同,因为对象不是使用它们的属性值进行比较,而是如果它们具有相同的引用。
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'
推荐阅读
- python - 我在 pandas 中导入一个 CSV 文件,但该列作为多索引导入
- webi - 如何重新定义维度?
- android - 无法在导航抽屉按钮单击时显示吐司
- r - 如何将 df 从列表中分离出来
- java - Java 中使用 ArrayList 的年龄过滤器
- javascript - 如何使用 v-text-field 自动填充
- linux - 如何让 Awk 在 shell 脚本中使用 Bash 数组变量?
- excel - 如何根据行之间的分隔符合并 Excel 中的行?
- python - Anaconda Prompt 创建的 Python New Env 未显示在 Jupyter Notebook 内核列表中
- r - Preview v. Adobe 浏览的 PDF 中带有绿色的奇怪颜色外观