打字稿中的管道(|)是什么意思?

2023-12-10

在浏览一些打字稿代码时@ng-bootstrap我找到了管道(|) 操作员。

export declare const NGB_PRECOMPILE: (typeof NgbAlert | typeof NgbTooltipWindow)[];

管道有什么用(|) 打字稿中的运算符?


这就是所谓的联合型在打字稿中。

联合类型描述的值可以是多种类型之一。

Pipe (|) 用于分隔每种类型,例如number | string | boolean是一个值的类型,可以是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'

操场


这是与问题中类似的示例:

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 or Test2.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

打字稿中的管道(|)是什么意思? 的相关文章

随机推荐