Mic*_*urz 12 destructuring typescript union-types object-destructuring
我收到以下错误:
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'.
}
Run Code Online (Sandbox Code Playgroud)
期望的结果:
typeof foo === string | undefined
typeof bar === number | undefined
Run Code Online (Sandbox Code Playgroud)
如何在没有显式类型保护的情况下访问属性,例如:
const foo = o.type === 1 ? o.foo : undefined
const bar = o.type === 2 ? o.bar : undefined
Run Code Online (Sandbox Code Playgroud)
这对我来说并不是一个真正的选择,因为我正在与大型联合一起工作,其中目标属性可能会也可能不会出现在许多对象上,这将是一团糟。
我还有什么其他选择?
您可以设置never未使用的属性,然后 TS 可以将这些属性的类型理解为可选。
type Type1 = { type: "1"; foo: string, bar?: never }
type Type2 = { type: "2"; foo?: never, bar: number }
type Union = Type1 | Type2
const doSomething = (object: Union) => {
const { type, foo, bar } = object
console.log(type, foo, bar)
}
doSomething({ type: "1", foo: "foo" }) // [LOG]: "1", "foo", undefined
doSomething({ type: "2", bar: 2 }) // [LOG]: "2", undefined, 2
Run Code Online (Sandbox Code Playgroud)
小智 1
这种行为有点道理,因为 TS 不知道它正在处理 Union 中的哪个对象,并且在某些情况下该属性不存在。
我不确定这是否是您正在寻找的,但您可以尝试类似的方法
type Union = { type: "1"; foo: string } | { type: "2"; bar: number };
function doSomething = (object: Union) => {
if ('foo' in object) {
const { foo } = object
}
if ('bar' in object) {
console.log(object.bar)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5711 次 |
| 最近记录: |