【发布时间】:2020-12-24 04:12:16
【问题描述】:
如何根据具有一个参数的函数正确推断返回类型,该参数是两种类型的并集?
我已经尝试了以下条件类型,但它不起作用(有关打字稿错误,请参阅内联注释):
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'
}
}
我还尝试了以下使用箭头函数的函数重载形式 (as described here),但这也会导致 TypeScript 错误并且还使用“any”,这会失去函数定义中的大部分打字优势:
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 one类似,不同的是函数参数是一个对象。
【问题讨论】:
标签: typescript