【问题标题】:Typescript & operator打字稿和运算符
【发布时间】:2016-02-25 19:53:34
【问题描述】:

我很难在 TypeScript 中找到 & 运算符的定义。我最近遇到了以下代码:

type IRecord<T> = T & TypedMap<T>;

那个操作符是做什么的,它与联合类型|有什么不同?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这看起来像是来自语言规范的Intersection Types 部分。具体来说,&amp;intersection type literal。至于它的作用:

    交集类型表示同时具有多种类型的值。交集类型 A 和 B 的值是类型 A 和类型 B 的值。交集类型是使用交集类型文字编写的(第 3.8.7 节)。

    规范继续提供有用的 sn-p 以更好地理解行为:

    interface A { a: number }  
    interface B { b: number }
    
    var ab: A & B = { a: 1, b: 1 };  
    var a: A = ab;  // A & B assignable to A  
    var b: B = ab;  // A & B assignable to B
    

    因为abA 类型 类型B,我们可以将它分配给a 和/或b。如果ab 只是B 类型,我们只能将其分配给b

    您分享的代码可能来自this comment on GitHub,其中提到了交叉点类型。

    【讨论】:

    【解决方案2】:

    值得注意的是,如果您更喜欢使用接口而不是类型(尽管它们在很大程度上相似),您通常可以使用interface extension 而不是type intersection,如下所示:

    // base type
    interface Shape {
      color: string;
    }
    
    // extension
    interface Square extends Shape {
      sideLength: number;
    }
    
    // intersection
    type Square = Shape & {
      sideLength: number;
    }
    

    另见Difference between extending and intersecting interfaces in TypeScript?

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 1970-01-01
      • 2020-12-13
      • 2021-07-23
      • 1970-01-01
      • 2022-09-30
      • 2020-07-26
      相关资源
      最近更新 更多