【发布时间】:2016-12-02 08:36:34
【问题描述】:
在浏览@ng-bootstrap 的一些打字稿代码时,我发现了 pipe(|) 运算符。
export declare const NGB_PRECOMPILE: (typeof NgbAlert | typeof NgbTooltipWindow)[];
typescript 中 pipe(|) 运算符有什么用?
【问题讨论】:
标签: typescript
在浏览@ng-bootstrap 的一些打字稿代码时,我发现了 pipe(|) 运算符。
export declare const NGB_PRECOMPILE: (typeof NgbAlert | typeof NgbTooltipWindow)[];
typescript 中 pipe(|) 运算符有什么用?
【问题讨论】:
标签: typescript
这在打字稿中称为union type。
联合类型描述的值可以是多种类型之一。
管道 (|) 用于分隔每种类型,例如,number | string | boolean 是可以是 number、string 或 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 或 Test2 的构造函数。
【讨论】:
something,我怎么知道它当前拥有的特定类型的对象?我希望这个答案也能回答这个问题。
typeof,对于类instanceof。或者它可以是用户定义的类型保护。视具体情况而定。更多信息在这里typescriptlang.org/docs/handbook/…
管道代表“或”。因此,在这种情况下,它表示允许任何一种声明的类型。也许很容易理解原始类型的联合:
let x: (string | number);
x = 1; //ok
x = 'myString'; //ok
x = true; //compilation error for a boolean
【讨论】:
thing: One | Two 两种类型都是具有不同属性的接口,它将合并(联合?)它们,并抱怨两者都不匹配彼此的属性。这不适用于原语,因为我不能只将对象与boolean 或其他东西合并