【问题标题】:What does the pipe(|) mean in typescript?打字稿中的管道(|)是什么意思?
【发布时间】:2016-12-02 08:36:34
【问题描述】:

在浏览@ng-bootstrap 的一些打字稿代码时,我发现了 pipe(|) 运算符。

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

typescript 中 pipe(|) 运算符有什么用?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这在打字稿中称为union type

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

    管道 (|) 用于分隔每种类型,例如,number | string | boolean 是可以是 numberstringboolean 的值的类型。

    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


    这是一个类似于问题中的示例:

    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,我怎么知道它当前拥有的特定类型的对象?我希望这个答案也能回答这个问题。
    • @Nawaz 你可以使用类型保护。对于原语,它可以是typeof,对于类instanceof。或者它可以是用户定义的类型保护。视具体情况而定。更多信息在这里typescriptlang.org/docs/handbook/…
    • 看起来工会手册链接现在已被弃用,并且“转到新页面”按钮没有任何用处。您可能希望将其更改为 this link
    【解决方案2】:

    管道代表“或”。因此,在这种情况下,它表示允许任何一种声明的类型。也许很容易理解原始类型的联合:

    let x: (string | number);
    
    x = 1; //ok
    x = 'myString'; //ok
    x = true; //compilation error for a boolean
    

    【讨论】:

    • 在JS中双流水线是逻辑或,单流水线是按位或。
    • 此外,它似乎只适用于原语,因为thing: One | Two 两种类型都是具有不同属性的接口,它将合并(联合?)它们,并抱怨两者都不匹配彼此的属性。这不适用于原语,因为我不能只将对象与boolean 或其他东西合并
    猜你喜欢
    • 2019-11-15
    • 2021-04-24
    • 2018-09-12
    • 2021-04-21
    • 2019-12-19
    • 2021-01-02
    • 2021-03-27
    • 2021-04-07
    相关资源
    最近更新 更多