I am dealing with a function that takes in a record of Handler<I, O>
and outputs a function that provides the O
value from one of the handlers:
type Handler<I, O> = { i: I, o: O, handler: (i: I) => O };
function handlerGroup<I, O>(handlers: Record<string, Handler<I, O>>): (key: string) => O {
return (key: string) => {
const { i, handler } = handlers[key];
return handler(i);
}
}
For instance:
const handleT1: Handler<number, number> = { i: 1, o: 1, handler: (i) => i }
const handleT2: Handler<number, string> = { i: 1, o: "1", handler: (i) => i.toString() }
handlerGroup({ T1: handleT1 }) //: (key: string) => number
handlerGroup({ T2: handleT2 }) //: (key: string) => string
The issue arises when I attempt to include more than one record:
// Type 'Handler<number, string>' is not assignable to type 'Handler<number, number>'.
// Types of property 'o' are incompatible.
// Type 'string' is not assignable to type 'number'.(2322)
handlerGroup({ T1: handleT1, T2: handleT2 }) // expected: (key: string) => number | string
This problem stems from how I defined the typing for handleGroup
, which I'm currently unsure how to tackle.
So my question remains, how can I enable handleGroup
to deduce all possible O
values based on the provided record?