【发布时间】:2020-09-10 21:42:46
【问题描述】:
我在缩小 typescript 中的联合类型时遇到了问题。
假设我们有两个接口和一个联合:
interface A {
flag: true
callback: (arg: string) => void
}
interface B {
flag?: false
callback: (arg: number) => void
}
type AB = A | B
这可以正确缩小范围:
const testA: AB = {
flag: true,
callback: arg => {
// typescript knows this is interface A and arg is a string
}
}
const testB: AB = {
flag: false,
callback: arg => {
// typescript knows this is interface B and arg is a number
}
}
但这不起作用:
const testC: AB = {
// we are implying flag: undefined
callback: arg => {
// typescript has no clue if this is A or B
// arg is implicitly any
}
}
我错过了什么?
提前致谢
【问题讨论】:
-
这可能有助于缩小您的问题:Typescript 实际上正在将正确的 testC 类型确定为 B,如 this playground 所示。所以我认为你的问题真的是:为什么它不能在
testC.callback中推断出参数arg的正确类型?
标签: typescript