How can I properly infer the return type based on a function that has one parameter that is a union of two types?
I've tried the following with conditional types, but it does not work (see inline comment for the typescript error):
type Status = 'statusType'
type GoalActivity = 'goalActivityType'
type Argument = { type: 'status'; status: Status | null } | { type: 'goalActivity'; goalActivity: GoalActivity | null }
const handleReaction = (arg: Argument): Argument extends { type: "status" } ? Status : GoalActivity => {
if (arg.type === 'status') {
return 'statusType' // Type '"statusType"' is not assignable to type '"goalActivityType"'.
} else {
return 'goalActivityType'
}
}
I've also tried the following using a form of function overloading for arrow functions (as described here), but this also results in a TypeScript error and also uses "any" which loses most of the typing benefits inside the function definition:
type Status = 'statusType'
type GoalActivity = 'goalActivityType'
type HandleReaction = {
(arg: { type: 'status'; status: Status | null }): Status
(arg: { type: 'goalActivity'; goalActivity: GoalActivity | null }): GoalActivity
}
const handleReaction: HandleReaction = (arg: any) => { // Type '"goalActivityType"' is not assignable to type '"statusType"'.
if (arg.type === 'status') {
return 'statusType'
} else {
return 'goalActivityType'
}
}
This question is similar to this one, but with the difference being that the function parameter is an object.