问题
首先,您没有为参数使用泛型类型,这将导致
typescript
永远不会根据您的输入推断出正确的类型(您可以想象泛型类型是参数,
tsc
需要它根据您的输入计算结果)。
简言之
const handleReaction = (arg: Argument): Argument extends { type: "status" } ? Status : GoalActivity => { // ... }
将始终返回
Status | GoalActivity
作为返回类型。
解决方案
当然,这里必须使用泛型类型作为参数。我将使用内联解释拆分您的代码:
type Status = 'statusType'
type GoalActivity = 'goalActivityType'
type StatusObj = { type: 'status'; status: Status | null };
type GoalActivityObj = { type: 'goalActivity'; goalActivity: GoalActivity | null }
type Argument = StatusObj | GoalActivityObj;
// Define returned type based on a input argument `T`
type ReturnType<T> = T extends StatusObj ? Status : GoalActivity;
// Generic type should be used here
const handleReaction = <T extends Argument>(arg: T): ReturnType<T> => {
if (arg.type === 'status') {
// Q: Why do we have to cast here?
// A: Any returned type can't assign to statement of `type ReturnType<T> ...`
// but luckily `tsc` still allows us to cast back since they are all string literal
return 'statusType' as ReturnType<T>;
} else {
return 'goalActivityType' as ReturnType<T>;
}
}