typescript 打字稿和运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33875609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript & operator
提问by ppoliani
I'm struggling to find the definition of the &
operator in TypeScript. I have recently come across the following code:
我正在努力&
在 TypeScript 中找到运算符的定义。我最近遇到了以下代码:
type IRecord<T> = T & TypedMap<T>;
What does that operator do, and how is it different from the union type |
?
该运算符有什么作用,它与联合类型|
有何不同?
回答by Sampson
This looks like it's from the Intersection Typesportion of the Language Specification. Specifically, the &
appears to be an intersection type literal. As for what it does:
这看起来像是来自语言规范的交集类型部分。具体来说,&
似乎是一个交集类型文字。至于它的作用:
Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. Intersection types are written using intersection type literals (section 3.8.7).
交集类型表示同时具有多种类型的值。交集类型 A & B 的值是同时属于类型 A 和类型 B 的值。交集类型是使用交集类型文字编写的(第 3.8.7 节)。
The spec goes on to offer a helpful snippet to better understand the behavior:
规范继续提供一个有用的片段来更好地理解行为:
interface A { a: number }
interface B { b: number }
var ab: A & B = { a: 1, b: 1 };
var a: A = ab; // A & B assignable to A
var b: B = ab; // A & B assignable to B
Because ab
is both of type A
andof type B
, we can assign it to a
and/or b
. If ab
were only of type B
, we could only assign it to b
.
因为ab
是 typeA
和type B
,我们可以将它分配给a
and/or b
。如果ab
只是类型B
,我们只能将它分配给b
.
The code you shared may be from this comment on GitHub, which mentions Intersection Types.
您分享的代码可能来自GitHub 上的这个评论,其中提到了 Intersection Types。