typescript :理解联合和交叉类型

标签 typescript union intersection

我试图在 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我希望它只允许我分配 ab但不是两者兼而有之。

有人可以给我一些关于这些类型的直觉吗?

最佳答案

鉴于以下情况:

interface A {
    a: number;
    c: number;
}

interface B{
    b: boolean;
    c: number;
}

联合类型的表达式A | B可分配给 AB .它必须具有来自 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/

相关文章:

javascript - TypeScript 接口(interface)未定义

tsql : Access query to TSQL union update conversion correct?

Excel在没有VBA的情况下查找两个数组的交集

javascript - 导入()文件中的 Node.js 数组为空

html - 在 Angular 中执行函数之前如何等待最后一次击键?

sql - UNION ALL 和 NOT IN 在一起

mysql - 如何在MYSQL中选择与其他表中的多行交集相匹配的行?

unity3d - 寻找线段-矩形交点

jquery - 单击按钮时是否可以按 Angular 滚动到页面底部?

mysql - 在此 union 语句中将 ORDER BY 放在哪里?