打字稿中的管道(|)是什么意思? [英] What does the pipe(|) mean in typescript?
问题描述
在浏览 @ng-bootstrap
的一些打字稿代码时,我发现了 pipe(|
) 运算符.
While browsing some typescript code of @ng-bootstrap
I have found pipe(|
) operator.
export declare const NGB_PRECOMPILE: (typeof NgbAlert | typeof NgbTooltipWindow)[];
pipe(|
) 运算符在打字稿中有什么用?
What is the use of pipe(|
) operator in typescript?
推荐答案
这叫做 联合类型 在打字稿中.
This is called union type in typescript.
联合类型描述了一个可以是多种类型之一的值.
A union type describes a value that can be one of several types.
管道(|
)用于分隔每种类型,例如number |字符串 |boolean
是值的类型,可以是 number
、string
或 boolean
.
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
.
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
是一个包含 Test1
或 Test2
的构造函数的数组.
x
is an array containing constructors of Test1
or Test2
.
这篇关于打字稿中的管道(|)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!