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

DAY 9 OF 30

Declaration merging

Yesterday, in one sentence

What is an interface in TypeScript, and how do you extend one?

Interview question

What is an intersection type in TypeScript?

If you declare the same interface name twice, TypeScript combines them into one. This is called declaration merging.

interface User {
  id: number;
}

interface User {
  name: string;
}

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

There is only ever one User, and it has both properties. A type aliasType Alias cannot do this. Declaring the same alias name twice is an error.

type Admin = { id: number };
type Admin = { name: string };
// ❌ Duplicate identifier 'Admin'

This is why interfacesInterface are described as open and type aliases as closed. An interface can be reopened and added to later. An alias is fixed once you write it.

Merging exists so that code you do not control can be extended. For example, the browser's window object is described by an interface called Window, which your own code can reopen to add to.

interface Window {
  appVersion: string;
}

window.appVersion; // string

That gives us a third row for the comparison table from day 8.

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

Check yourself

What happens if you declare interface User twice in the same scope?
What is declaration merging in TypeScript?