I'm looking to utilize Maps instead of object maps to define keys and values. However, it appears that Typescript doesn't fully support index types for ES6 Maps. Are there any alternatives or workarounds available?
Furthermore, I want to enforce type safety for the values in the Map, ensuring that each entry corresponds to the correct key.
Below is some pseudocode outlining what I hope to achieve:
type Keys = 'key1' | 'key2';
type Values = {
'key1': string;
'key2': number;
}
/** Should trigger a missing entry error */
const myMap = new Map<K in Keys, Values[K]>([
['key1', 'error missing key'],
]);
/** Should trigger a 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: additional code relating to my specific scenario
enum Types = {
ADD = 'ADD',
REMOVE = 'REMOVE',
};
/** Seeking type-safety and autocompletion for the payload parameter */
const handleAdd = (state, payload) => ({...state, payload});
/** Want to guarantee that all types in Types are covered */
export const reducers = new Map([
[Types.ADD, handleAdd],
[Types.REMOVE, handleRemove]
]);