【发布时间】:2020-04-23 00:53:37
【问题描述】:
我最近开始学习 TypeScript,对类型交集/联合的概念有点困惑。在下面的代码 sn-p 中,我假设编译器应该警告关于缺少参数 z 的错误,但它不会。
interface DataA { x: string, y: string, z: string }
interface DataB { x: string }
interface A { id: string, data: DataA }
interface B { id: string, data: DataB }
type C = A & B
type D = B
type X = C | D
function bar(val: X) {}
bar({
id: "some id",
data: {
x: "some data",
y: "some data"
}
});
【问题讨论】:
-
你能解释一下为什么你会假设编译器会抱怨缺少
z吗?您传递给var的值是一个有效的B,可以分配给X = B | C。如果有的话,它可能会抱怨额外的y,但properties of non-discriminated unions present in at least one member do not trigger excess property warnings。如果你能解释你的思考过程,我也许可以解释它与编译器所做的不同之处。祝你好运。 -
我的假设是 x、y 和 z 应该存在或只存在 x。因此,它将对应于 A 或 A&B,但不是介于两者之间。感谢您的链接,它似乎与我的问题直接相关。
标签: typescript typescript-types