Hello community! Seeking assistance for annotating a polymorphic function. I have multiple types that share a common key "type" along with other keys:
type T1 = { type: 't1', someKey: number };
type T2 = { type: 't2', anotheKey: string };
type T3 = { type: 't3', andAnotherKey: boolean };
type T = T1 | T2 | T3;
I also have a map of functions. Each key in this map corresponds to the "type" field, and the value is a function taking an argument of the respective type:
const TYPE_FN_MAP = {
t1: (argT1: T1) => argT1.someKey,
t2: (argT2: T2) => argT2.anotheKey,
t3: (argT3: T3) => argT3.andAnotherKey,
} as const
How do I annotate the polymorphic function:
const polymorphicFn = (argT) => TYPE_FN_MAP[argT.type](argT);
The idea is that when adding a new type, simply extend the TYPE_FN_MAP with a function taking an argument of that type, while keeping the polymorphicFn function unchanged. If the "type" field is forgotten in a new type, TypeScript will flag an error in the polymorphicFn function.