【发布时间】:2021-10-25 21:02:39
【问题描述】:
是否可以在 Map 的 Key/Value 类型之间创建某种关系?
我的意思是,如果我使用一个对象,很容易创建类似的东西:
type TObject = { key: string; value: number } | { key: number; value: string }
const obj = { key: 1, value: 'Something' } // Perfect
const obj = { key: 'Something', value: 1 } // Perfect
const obj = { key: 1, value: 1 } // Error
但是,我不知道如何为地图实现此行为
const map = new Map<string | number, number | string>();
map.set(1, 'a'); // Perfect
map.set('a', 1); // Perfect
map.set(1, 1); // I want to display an error, with the type above : this will works since <number, number> is a possible type
map.set('a', 'a'); // I want to display an error, currently this will works since <string, string> is a possible type
【问题讨论】:
-
您在寻找
Map<string, number> | Map<number, string>吗?还是您想要一张包含混合类型条目的地图?
标签: javascript typescript types typescript-typings typescript-generics