我希望使用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 = new Map<K in Keys, Values[K]>([
['key1', 'all good'],
['key2', 42],
]);
编辑:更多的代码部分描述了我的使用情况
enum Types = {
ADD = 'ADD',
REMOVE = 'REMOVE',
};
/** I would like type-safety and autocompletion for the payload parameter */
const handleAdd = (state, payload) => ({...state, payload});
/** I would like to ensure that all types declared in Types are implemented */
export const reducers = new Map([
[Types.ADD, handleAdd],
[Types.REMOVE, handleRemove]
]);
字符串 -> 对象
的。对于reducers,我希望函数的参数可以推断出它们将接收哪种类型作为有效负载。我的actions符合FSA标准,具有类型和有效负载作为属性。 - Nikolai Hegelstad