CodePark/ questions / Types vs interfaces
START PRACTICINGPRACTICE
Frontend question · TypeScript › Types vs interfaces

Explain the difference between a union type A | B and an intersection type A & B.

type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };

type Pet = Cat | Dog;      // one or the other
type CatDog = Cat & Dog;   // both at once

A union A | B means the value is one of the types. An intersection A & B means the value is all of the types at once.

With a union, before you narrow you can only use members that every option has. On Pet you can read name, because both Cat and Dog have it. You cannot call meow() until you check which one it is. Narrowing means a check that tells TypeScript the more specific type.

With an intersection, the value must have every member of both types. So CatDog has name, meow and bark. Intersections are often used to combine object types. For example, you can add extra props to a base props type.

If an intersection combines types that cannot both be true, such as string & number, the result is never. never is the type with no values, because no value can be a string and a number at the same time.

  • A union A | B means the value is one of the types.
  • Before narrowing, you can only use members that all union members share.
  • An intersection A & B means the value has all members of every type.
  • An intersection of incompatible types, like string & number, becomes never.