1. 程式人生 > 其它 >Typescript & operator

Typescript & operator

Typescript & operator

Ask Question Asked 6 years, 6 months ago Modified 5 months ago Viewed 26k times 54

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

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

What does that operator do, and how is it different from the union type |?

Share   edited Nov 23, 2015 at 19:19 Sampson 259k7373 gold badges529529 silver badges557557 bronze badges asked Nov 23, 2015 at 16:15 ppoliani 4,44633 gold badges3232 silver badges6060 bronze badges
Add a comment

2 Answers

77  

This looks like it's from the Intersection Types portion of the Language Specification. Specifically, the & is 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.

Share   edited Dec 20, 2021 at 19:32 KyleMit 34.9k6060 gold badges418418 silver badges598598 bronze badges answered Nov 23, 2015 at 16:21 Sampson 259k7373 gold badges529529 silver badges557557 bronze badges Add a comment 1

Worth noting that if you'd prefer to use interfaces over types (although they're largely similar) that you can typically use interface extension instead of type intersection like this:

// base type
interface Shape {
  color: string;
}

// extension
interface Square extends Shape {
  sideLength: number;
}

// intersection
type Square = Shape & {
  sideLength: number;
}

See AlsoDifference between extending and intersecting interfaces in TypeScript?