首页 > 解决方案 > 带有单例类型的打字稿联合类型无法编译

问题描述

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

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

标签: typescript

解决方案


这是类型检查的一个怪癖。三元表达式a ? "primary" : "secondary"将具有类型,"primary" | "secondary"这意味着对象字面量的类型为{ id : "primary" | "secondary" }.

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

修复的简单方法是将支票移到外面:

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

或者使用类型断言。


推荐阅读