DEV Community

Discussion on: Types vs. Interfaces in Typescript

Collapse
harisharaju1 profile image
Harish Raju

So what is the difference between combining two types or interfaces, using '&' and using '|'.

Collapse
diasbruno profile image
Bruno Dias

With | you have a choice A | B (reads type A or B), and &, you can consider like a union of both types A and B.

Collapse
codinghusi profile image
Gerrit Weiermann

The & will merge the types, so all the properties of both types will be in the resulting type.

The | will give you the option to choose between all the given types, and use one of them, rather than all together :)

Collapse
peerreynders profile image
peerreynders

See Naming of TypeScript's union and intersection types:

type Dog = {
  breed: string;
};

// Intersection
type Bulldog = {
  isCute: boolean;
} & Dog;

const winston: Bulldog = {
  breed: 'Bulldog',
  isCute: false,
};

// Union
type Pet = {
  name: string
} | Dog;

const cat: Pet = {
  name: 'Fluffykins'
};

const fido: Pet = {
  name: 'froufrou',
  breed: 'Maltese'
};

const dog: Pet = {
  breed: 'Boston Terrier'
}
Enter fullscreen mode Exit fullscreen mode

intersection of types (&): the shape of the data has to conform to the constraints of all the intersected types simultaneously.

union of types (|): the shape of the data has to conform to the constraints of at least one of the unioned types.

Collapse
harisharaju1 profile image
Harish Raju

thank you for explaining along with code snippets.....appreciate it!!