打字稿:了解联合和交叉点类型 [英] Typescript: understanding union and Intersection types

查看:108
本文介绍了打字稿:了解联合和交叉点类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解打字稿中的并集和相交类型,但是我无法弄清楚这种情况:游乐场链接

I am trying to get an intuition about Union and Intersection types in typescript, but I can't figure out this case: 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,
}

为什么我允许将两个值都放在交集类型中?两个接口之间的交集为空.如果我将&读为AND,那么我很清楚为什么它允许我同时添加两个道具,但是随后我应该将|关键字读为OR,我希望它允许我仅分配ab,但不能两者都显示.

Why am I allow to put both values in the intersection type? The intersection between the two interfaces is empty. If I read the & as AND then it's clear to me why it allows me to add both props, but then I should read the | keyword as OR and I would expect it to allow me to assign only a or b but not both.

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

Can someone give me some intuition about those types?

推荐答案

给出以下内容:

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

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

联合类型A | B的表达式可分配给AB.它必须具有AB(或两者)

Expression of Union type A | B is assignable to either A or B. It must have properties from A or B (or both)

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这样的类型具有什么操作? 只有属于AB

But what operations does a type like A | B have? Only these that belong to both A and B

oA.c = 1; // valid

交叉点类型A & B(如果可同时分配给A和B)(因此必须同时具有A和B的属性).

Intersection type A & B, if it is assignable to both A and B (and therefore must have properties of both A and B).

const obj: A & B = {
    a: 6,
    b: true
}

更新

您问为什么示例中的A& B可以使用b属性?不能分配给A类型"

You ask "why does A & B in your example can take b prop? it's not assignable to type A"

这显然是不正确的. 具有A所有属性的任何类型都可以分配给A.其他属性无害:

This is clearly not true. Any type that has all properties of A can be assigned to A. Extra properties make no harm:

const aAndExtraProp = {
  a: 6,
  d: 6
};

const ca0: A = aAndExtraProp;

多余的属性检查用于对象文字:

对象文字在分配给其他变量或作为参数传递时会受到特殊对待,并进行过多的属性检查.如果对象文字具有目标类型"所没有的任何属性,则会出现错误:

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
};

这篇关于打字稿:了解联合和交叉点类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆