Typescript & operator

后端 未结 1 1811
灰色年华
灰色年华 2020-12-05 03:58

I\'m struggling to find the definition of the & operator in TypeScript. I have recently come across the following code:



        
相关标签:
1条回答
  • 2020-12-05 04:54

    This looks like it's from the Intersection Types portion of the Language Specification. Specifically, the & appears to be an intersection type literal. As for what it does:

    Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. Intersection types are written using intersection type literals (section 3.8.7).

    The spec goes on to offer a helpful snippet to better understand the behavior:

    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
    

    Because ab is both of type A and of type B, we can assign it to a and/or b. If ab were only of type B, we could only assign it to b.

    The code you shared may be from this comment on GitHub, which mentions Intersection Types.

    0 讨论(0)
提交回复
热议问题