小编Nik*_*tad的帖子

Typescript:如何根据对象键/值类型在 ES6 映射中创建条目

我想使用 Map 而不是对象映射来声明一些键和值。但是 Typescript 似乎不支持 ES6 Map 的索引类型,这是正确的吗?有什么解决方法吗?

此外,我还希望使值类型安全,以便映射中的每个条目都具有与键对应的值的正确类型。

这是一些伪代码,描述了我想要实现的目标:

type Keys = 'key1' | 'key2';

type  Values = {
  'key1': string;
  'key2': number;
}

/** Should display missing entry error */
const myMap = new Map<K in Keys, Values[K]>([
  ['key1', 'error missing key'],
]);

/** Should display wrong value type error for 'key2' */
const myMap = new Map<K in Keys, Values[K]>([
  ['key1', 'okay'],
  ['key2', 'error: this value should be number'],
]);

/** Should pass */
const myMap = …
Run Code Online (Sandbox Code Playgroud)

typescript ecmascript-6 typescript-generics union-types es6-map

9
推荐指数
1
解决办法
3579
查看次数