【问题标题】:Typescript : Es6 Map TS Type Relation打字稿:Es6 Map TS 类型关系
【发布时间】: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&lt;string, number&gt; | Map&lt;number, string&gt;吗?还是您想要一张包含混合类型条目的地图?

标签: javascript typescript types typescript-typings typescript-generics


【解决方案1】:

定义一个覆盖Map 的自定义类型,以将调用签名指向您想要的。

interface CustomMap<T, U> extends Map<T | U, T | U> {
  get(key: T): U | undefined;
  get(key: U): T | undefined;
  set(key: T, value: U): this;
  set(key: U, value: T): this;
}

const map: CustomMap<string, number> = new Map();
map.set(1, 'a'); // OK
map.set('a', 1); // OK
map.set(1, 1); // error as expected
map.set('a', 'a'); // error as expected
map.size; // OK, not overridden, still a number
map.delete(1); // OK
map.delete('a'); // OK

【讨论】:

  • 你是救生员……勒克斯。为了使用更通用的解决方案,我使用了: interface CustomMap extends Map ... 谢谢
  • 很高兴它为您工作并帮助您提出更好的解决方案!感谢您认识 Lux。 ?
猜你喜欢
  • 2020-05-25
  • 2021-12-03
  • 1970-01-01
  • 2020-05-02
  • 2020-07-09
  • 2020-06-25
  • 2020-08-30
  • 2018-11-30
  • 2022-10-14
相关资源
最近更新 更多