打字稿中的管道(|)是什么意思? [英] What does the pipe(|) mean in typescript?

查看:40
本文介绍了打字稿中的管道(|)是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览 @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 是值的类型,可以是 numberstringboolean.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆