DAY 9 OF 30
Declaration merging
Yesterday, in one sentence
A named object type, written with the interface keyword. You extend one with
extends, which gives the new interface every property from the one it
extends.
Did you say:
- ✓a named object type
- ✓written with the `interface` keyword
- ✓`extends` gives it every property from the one it extends
Interview question
A type that combines two or more types into one, written with &. The value must
have everything from all of them.
Did you say:
- ✓combines two or more types into one
- ✓written with `&`
- ✓the value needs everything from all of them
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.
| Feature | Type alias | Interface |
|---|---|---|
| Types it can name | Any type: object, union, array, tuple, intersection | Object types only |
Can use the extends keyword | No ❌ | Yes ✅ |
| Can be declared twice and merged | No ❌ | Yes ✅ |
Check yourself
interface User twice in the same scope?Interfaces are open, so declaring the same name twice adds to it rather than replacing or erroring.
Declaring the same interface name more than once, and TypeScript combining them into a single interface with all the properties. Type aliases cannot do this.
Did you say:
- ✓the same interface name declared more than once
- ✓TypeScript combines them into one
- ✓type aliases cannot do this