I would like to use Map instead of object map to declare some keys and values. But Typescript doesn't seem to support index types for ES6 Map, is that correct and are there any workarounds?
Additionally, I would like to make the values type-safe as well so that each entry in the map has the correct type for the value corresponding to the key.
Here is some pseudo-code that describes what I am trying to achieve:
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],
]);
Edit: more code that partially describes my use case
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]
]);