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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:15:12  来源:igfitidea点击:

What does the pipe(|) mean in typescript?

typescript

提问by Jobin

While browsing some typescript code of @ng-bootstrapI 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 | booleanis 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'

Playground

操场



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

xis an array containing constructors of Test1orTest2.

x是一个包含Test1or 的构造函数的数组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