number field is the union of the set of all strings and the set of all numbers. The set of things that can be assigned to a string & number is nothing because there is no overlap in the set of all strings and the set of all numbers.

问题描述 投票:0回答:1

I think you're picturing it as a set operator on the fields rather than a set operator of the sets of what each type represents.

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

我想对typecript中的union和intersection有一个直观的认识,但是这个案例我想不通。&Playground LinkAND为什么我可以把两个值都放在交集类型中?两个接口之间的交集是空的。如果我读取 | 作为 OR 那么我就明白为什么它允许我添加这两个道具了,但是我应该读懂了 a 关键词为 b 我希望它能允许我只指定

但不能兼而有之。
typescript union intersection
1个回答
1
投票

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

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

A | B我想在typescript中对Union和Intersection有一个直观的认识,但是这个案例我想不通。Playground Link 接口A { a: number; } 接口B{ b: boolean; } ... ...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 | BA (或两者)B

oA.c = 1; // valid

但像 A & B 只有这些属于两个人的

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

交叉口类型

如果它可以同时分配给A和B(因此必须同时具有A和B的属性)。

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

const ca0: A = aAndExtraProp;

更新你问 "为什么你的例子中的A & B可以取b道具,它不能分配给类型A"这显然是不对的.任何具有A的所有属性的类型都可以分配给A.额外的属性使没有伤害。

你可能被以下内容搞糊涂了

超额财产检查

const ca1: A = {
  a: 6,
  d: 6 //ERROR
};
的对象字元。

1
投票
对象字面意义得到了特殊的处理,并在将它们赋值给其他变量,或将它们作为参数传递时,进行了多余的属性检查。如果一个对象字面值有任何 "目标类型 "没有的属性,你会得到一个错误。

从联合类型接受的角度来思考 可以分配给字符串的一组东西////////////////////////////////////////////////////////////////////////////////////////////////////////////

这是数学术语:一个 "类型 "是其所有可能的值的集合,例如boolean = {true, false};。现在,类型 T 和 U 的联合是一个由 T 中的值或 U 中的值组成的集合(即 T 与 U 合并);同样,T 和 U 中的值的交集(即它们的共同部分)。

一个成员如果是在所有可能的值上,那么它就是可访问的。对于联合,类型为T/www.reddit.comrtypescriptcomments9qduq3why_is_type_intersection_called_like_that_its的值。

© www.soinside.com 2019 - 2024. All rights reserved.