Want a faster signal before interviews? Take the Interview Ready Check →

DAY 8 OF 30

Interfaces

Yesterday, in one sentence

What is the difference between a union type and an intersection type?

Interview question

What kinds of type can a type alias name?

Type aliasesType Alias are not the only way to name an object typeObject Type. TypeScript has a second way of defining one, with different features, called an interface.

An interface names an object type. You write interface, the name, and the shape in braces. There is no =.

interface User {
  readonly id: number;
  name: string;
  nickname?: string;
}

const xavier: User = { id: 1, name: "Xavier" };

Everything inside works the same as in an object type. readonly and optional properties behave exactly as they did on day 5.

An interface can build on another interface with the extends keyword. The new interface gets every property from the interface it extends, plus whatever properties it adds itself.

interface User {
  readonly id: number;
  name: string;
}

interface Mutant extends User {
  power: string;
}

const jean: Mutant = {
  id: 2,
  name: "Jean",
  power: "telepathy",
};

An interface can extend more than one interface at a time. You list them after the extends keyword, separated by commas.

interface Timestamps {
  readonly createdAt: string;
}

interface Student extends User, Timestamps {
  year: number;
}

The extends keyword is exclusive to interfaces. A type alias cannot use it.

Interfaces and type aliases overlap, but they are not the same. The difference between them is one of the most common TypeScript interview questions, and we will add to this table as more differences come up. Here are the first two.

FeatureType aliasInterface
Types it can nameAny type: object, union, array, tuple, intersectionObject types only
Can use the extends keywordNo ❌Yes ✅

Check yourself

Which of these is not a valid interface?
What is an interface in TypeScript, and how do you extend one?