I have a discriminate union type Actions. For each action, I have a different handler function, returning a different result.
I now need a generic handler function that based on action.type calls the respective handler function and returns its result. The type signature of this function should be such that TypeScript can infer the shape of the result based on the called parameter. I achieve this with the type signature const handler = <A extends Action>(a: A): HandlerMap[A['type']] => .... However, TypeScript complains in the implemented switch statement, that the return is invalid:
Type 'Result1' is not assignable to type 'HandlerMap[A["type"]]'.
Type 'Result1' is not assignable to type 'Result1 & Result2'.
Type 'Result1' is not assignable to type 'Result2'.
What am I missing/doing wrong?
Here's the full code:
type Action1 = { type: 'A1'; input: { i: string } }
type Result1 = { result: string }
const handler1 = (a: Action1): Result1 => ({ result: a.input.i + '!' })
type Action2 = { type: 'A2'; input: { x: number } }
type Result2 = { result: { r2: number } }
const handler2 = (a: Action2): Result2 => ({ result: { r2: a.input.x + 1 } })
type Action = Action1 | Action2
type HandlerMap = {
A1: Result1
A2: Result2
}
const handler = <A extends Action>(a: A): HandlerMap[A['type']] => {
switch (a.type) {
case 'A1': return handler1(a) // <--Compiler complains here
case 'A2': return handler2(a)
default: return undefined
}
}