我试图在 typescript 中获得关于 Union 和 Intersection 类型的直觉,但我无法弄清楚这种情况:Playground Link
interface A {
a: number;
}
interface B{
b: boolean;
}
type UnionCombinedType = A | B;
type IntersectionType = A & B;
const obj: UnionCombinedType = {
a: 6,
b: true,
}
const obj2: IntersectionType = {
a: 6,
b: true,
}
为什么我允许将两个值都放在交集类型中?两个接口(interface)之间的交集是空的。如果我阅读
&
如AND
那么我很清楚为什么它允许我添加两个 Prop ,但是我应该阅读 |
关键字为 OR
我希望它只允许我分配 a
或 b
但不是两者兼而有之。有人可以给我一些关于这些类型的直觉吗?
最佳答案
鉴于以下情况:
interface A {
a: number;
c: number;
}
interface B{
b: boolean;
c: number;
}
联合类型的表达式
A | B
可分配给 A
或 B
.它必须具有来自 A
的属性或 B
(或两者)const oA: A | B = {
a: 6,
c: 6
}
const oB: A | B = {
b: true,
c: 6
}
const oC: A | B = {
a: 6,
b: true
c: 6
}
但是像
A | B
这样的类型有什么操作?有?仅属于
A
的那些和 B
oA.c = 1; // valid
路口类型
A & B
, 如果它可以分配给 A 和 B(因此必须同时具有 A 和 B 的属性)。const obj: A & B = {
a: 6,
b: true
}
更新
您问“为什么您的示例中的 A & B 可以使用 b Prop ?它不能分配给类型 A”
这显然不是真的。
具有 A 的所有属性的任何类型都可以分配给 A。额外的属性没有害处:
const aAndExtraProp = {
a: 6,
d: 6
};
const ca0: A = aAndExtraProp;
你可能对 Excess Property Checks 感到困惑对于对象文字:
Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error:
const ca1: A = {
a: 6,
d: 6 //ERROR
};
关于 typescript :理解联合和交叉类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370779/