我收到以下错误:
type Union = { type: "1"; foo: string } | { type: "2"; bar: number };
function doSomething = (object: Union) => {
const { foo } = object
// ^ TS2339: Property 'foo' does not exist on type 'Union'.
console.log(object.bar)
// ^ TS2339: Property 'bar' does not exist on type 'Union'.
}
期望的结果:
typeof foo === string | undefined
typeof bar === number | undefined
如何在没有明确类型保护的情况下访问属性,例如:
const foo = o.type === 1 ? o.foo : undefined
const bar = o.type === 2 ? o.bar : undefined
这对我来说不是一个真正的选择,因为我正在使用大型联合,其中目标属性可能存在也可能不存在于许多对象上,这将是一团糟。
我还有什么其他选择?