typescript 管道(|)在打字稿中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38628115/
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
What does the pipe(|) mean in typescript?
提问by Jobin
While browsing some typescript code of @ng-bootstrap
I have found pipe(|
) operator.
在浏览一些打字稿代码时,@ng-bootstrap
我发现了 pipe( |
) 运算符。
export declare const NGB_PRECOMPILE: (typeof NgbAlert | typeof NgbTooltipWindow)[];
What is the use of pipe(|
) operator in typescript?
|
打字稿中管道()运算符的用途是什么?
回答by Aleksey L.
This is called union typein typescript.
这在打字稿中称为联合类型。
A union type describes a value that can be one of several types.
联合类型描述的值可以是多种类型之一。
Pipe (|
) is used to separate each type, so for example number | string | boolean
is the type of a value that can be a number
, a string
, or a boolean
.
管道 ( |
) 用于分隔每种类型,因此例如number | string | boolean
可以是 a number
、 astring
或 a的值的类型boolean
。
let something: number | string | boolean;
something = 1; // ok
something = '1'; // ok
something = true; // ok
something = {}; // Error: Type '{}' is not assignable to type 'string | number | boolean'
And here's an example similar to one in the question:
这是一个类似于问题中的示例:
class Test1 {
public a: string
}
class Test2 {
public b: string
}
class Test3 {
}
let x: (typeof Test1 | typeof Test2)[];
x = [Test1]; //ok
x = [Test1, Test2]; //ok
x = [Test3]; //compilation error
x
is an array containing constructors of Test1
orTest2
.
x
是一个包含Test1
or 的构造函数的数组Test2
。
回答by cham
The pipe represents 'or'. So in this context it says that either of the declared types is allowed. Perhaps it is easy to understand a union with primitive types:
管道代表“或”。因此,在这种情况下,它表示允许声明的任何一种类型。也许很容易理解具有原始类型的联合:
let x: (string | number);
x = 1; //ok
x = 'myString'; //ok
x = true; //compilation error for a boolean