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

无法编译带有单例类型的Typescript联合类型,typescript,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.

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

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"'.

这是一种类型检查的怪癖。三元表达式
a?“primary”:“secondary”
的类型为
“primary”|“secondary”
这意味着对象文本的类型为
{id:“primary”|“secondary”}

检查联合的方式是,要使对象文字与联合兼容,它必须至少与联合的一个成员兼容。问题是上面的对象文本类型与两个联合成员都不兼容,因此我们最终会出现错误

修复的简单方法是将支票移出:

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

或者使用类型断言。

显然这是按预期工作的

奇怪,尤其是代码
type X={id:“primary”|“secondary”|“treative”}&{inversed?:false}type Xid=“primary”|“secondary”|“treative”
示例代码过于简化。实际类型包含更多字段。这里重要的一点是,在第三种类型中,inversed必须为false。示例代码过于简化。如果我把这个条件移得更远,我将不得不复制一些代码。@Bomgar我想可能是这样的。不幸的是,唯一的其他选项是类型断言或
对象。赋值(a?{id:“primary”作为“primary”}:{id:“secondary”作为“secondary”},{})