I am working on creating a type-safe function for retrieving values from a map. The function needs to handle specific logic in my use case, which is why I require it beyond this simple example below:
enum ExampleA {
A = 'A'
}
enum ExampleB {
B = 'B'
}
const mapA = {
[ExampleA.A]: 'a'
};
const mapB = {
[ExampleB.B]: 'b'
};
type AllMaps = typeof mapA | typeof mapB;
type AllKeys = ExampleA | ExampleB;
// There is a type error here due to the key not existing on both maps
const typeSafeMapValueGetter = (map: AllMaps, key: AllKeys) => map[key];
typeSafeMapValueGetter(mapA, ExampleA.A);
I'm unsure how to proceed further with this challenge. I initially wanted to avoid using generics to ensure developers specify the map and key types they are using. However, if there is a way to incorporate generics so that TypeScript can infer the expected key type based on the provided map type, that would be ideal. Thank you for any assistance!