Merging Declarations in TypeScript

John Au-Yeung
Level Up Coding
Published in
6 min readJan 27, 2020

--

Photo by Mikhail Vasilyev on Unsplash

With TypeScript, we can declare many entities that don’t exist in vanilla JavaScript like interfaces, enums, and type alias. Sometimes, these types have to be merged together into one, like when we try to derive a new class from multiple classes or interfaces. This means that there are rules for merging them together. The process of declaration merging is the combining of multiple members from different sources with overlapping member names or types.

Basic Rules of Merging Interfaces

Merging interfaces is the simplest and most common operation type of declaration merging. The most basic case is that 2 interfaces have no overlapping members. In this case, they just get merged together mechanically into one. For example, if we have 2 Person interfaces like we do in the following code:

interface Person {
name: string;
}
interface Person {
age: number;
}

Then they’ll just be merged together into one when we declare a variable with the Person type. For example, we can write something like:

let person: Person = {
name: 'Jane',
age: 20
}

Then TypeScript would accept this code and compile and run the code.

If there’re any overlap of non-function members, then they must be unique. Otherwise, they must have the same type. For example, if we have:

interface Person {
name: string;
age: string;
}
interface Person {
age: number;
}

Then we get the following errors:

Subsequent property declarations must have the same type.  Property 'age' must be of type 'string', but here has type 'number'.(2717)input.ts(3, 5): 'age' was also declared here.

Also when 2 interfaces are being merged, whatever is in the second interface will overwrite the members of the first one if the first one has overlapping members with the second one. For function members, they’ll just be combined together as overloads of the same function. For example, if we have the following interface declarations:

interface Animal { };
interface Sheep { };
interface Dog { };
interface Cat { };

--

--