我想使用 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