3

我收到以下错误:

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

这对我来说不是一个真正的选择,因为我正在使用大型联合,其中目标属性可能存在也可能不存在于许多对象上,这将是一团糟。

我还有什么其他选择?

4

3 回答 3

2

对于未在所有联合成员上定义的属性,请检查访问对象类型联合中的属性失败中的注释 #12815

这里的问题是,因为 B 没有声明 a 属性,它可能在运行时具有任何可能类型的 a 属性(因为您可以将具有任何属性集的对象分配给 B,只要它具有 ab字符串类型的属性)。您可以使其工作在 B 中显式声明 a: undefined 属性(从而确保 B 不会有一些随机的 a 属性):

type A = { a: string; } 
type B = { b: string; a: undefined }
type AorB = A | B;

declare const AorB: AorB;

if (AorB.a) {
   // Ok
}
于 2021-01-15T21:50:15.573 回答
0

我发现最方便的方法是根据变量的类型转换变量。

type Type1 = { type: "1"; foo: string }
type Type2 = { type: "2"; bar: number }    
type Union = Type1 | Type2

function doSomething = (object: Union) => {
    const { foo } = object as Type1
    const { bar } = object as Type2
    const { type } = object  
}
于 2021-10-06T15:49:04.093 回答
0

这种行为有点道理,因为 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)
  }
}

这里是游乐场

于 2021-01-15T21:16:34.093 回答