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"'.
解决方案
这是类型检查的一个怪癖。三元表达式a ? "primary" : "secondary"
将具有类型,"primary" | "secondary"
这意味着对象字面量的类型为{ id : "primary" | "secondary" }
.
检查联合的方式是,要使对象字面量与联合兼容,它必须与联合的至少一个成员兼容。问题是上面的对象字面量类型与联合成员都不兼容,所以我们最终会出错。
修复的简单方法是将支票移到外面:
const x3: X = a ? { id: "primary" } : { id: "secondary" }
或者使用类型断言。
推荐阅读
- airflow - 使用 .net 控制台批处理应用程序进行气流编排
- javascript - Snowpack 无法从 node_modules 导入 JavaScript
- arrays - 如何将一个随机预制件限制为仅使用一次,但将一大堆预制件随机放置在其他对象之上?
- javascript - 如何解决:安装 PDF 而不是用 react-pdf 打开?
- rabbitmq - RabbitMQ:Publisher Confirm 中的奇怪行为
- java - Java LinkedList实现插入方法第0次索引插入处理
- c++ - 如何为使用“std::variant”的类型实现赋值运算符?
- python - Pandas 不同的采样大小
- python - 通过 Web 元素进行迭代
- javascript - Vue
不可点击