单例类型的Typescript联合类型无法编译

时间:2019-02-08 13:06:42

标签: typescript

我不明白为什么它不能编译:

type X = {
  id: "primary"
  inverted?: boolean
} | {
  id: "secondary"
  inverted?: boolean
} | {
  id: "tertiary"
  inverted?: false
}


const a = true
const x: X = {
  id: a ? "primary" : "secondary"
}
在任何一种情况下,

x均应为有效的X。

但是编译器抱怨:

test.ts:14:7 - error TS2322: Type '{ id: "primary" | "secondary"; }' is not assignable to type 'X'.
  Type '{ id: "primary" | "secondary"; }' is not assignable to type '{ id: "tertiary"; inverted?: false; }'.
    Types of property 'id' are incompatible.
      Type '"primary" | "secondary"' is not assignable to type '"tertiary"'.
        Type '"primary"' is not assignable to type '"tertiary"'.

2 个答案:

答案 0 :(得分:3)

这是类型检查的怪癖。三元表达式a ? "primary" : "secondary"的类型为"primary" | "secondary",这意味着对象文字的类型为{ id : "primary" | "secondary" }

检查联合的方式是,要使对象文字与联合兼容,它必须与联合的至少一个成员兼容。问题在于上面的对象文字类型与任何一个union成员都不兼容,因此最终导致错误。

简单的解决方法是将支票移到外面:

const x3: X = a ? { id: "primary" } : { id: "secondary" } 

或使用类型断言。

答案 1 :(得分:1)