Declaration merging

Intermediate · 2 min

How TypeScript combines declarations that share a name: interfaces, namespaces, functions, classes and enums, and why type aliases can't merge.

Before thisType aliases vs interfacesExtending interfaces and intersection types

Matt Pocock · 2 min

Declaration merging

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Matt PocockReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • When two interface declarations share a name in the same scope, TypeScript merges them into one interface containing the members of both.
  • A non-function property declared in both halves must have the same type in each, or the compiler reports that subsequent property declarations must have the same type.
  • Methods with the same name don't conflict; they become overloads of one method, with the later declaration's overloads placed first.
  • Namespaces can merge with other namespaces and with functions, classes and enums of the same name, which is how you attach extra properties or nested types to them.
  • A class can merge with an interface of the same name, which adds members to the class's instance type without any check that the class actually provides them.
  • Type aliases never merge: an alias binds one name to one finished type, so declaring it twice is a duplicate-identifier error.

Why a type would want to be reopened

TypeScript’s own standard library is split across many files. lib.es5.d.ts declares interface Array<T> with methods like map and filter. When you raise your target to ES2015, another file, lib.es2015.core.d.ts, declares interface Array<T> again with just the new methods: find, fill, copyWithin. Later lib files add includes, flat, at, and so on. Nobody edits the original declaration. Each file reopens it and adds what that edition of JavaScript brought.

That’s declaration merging: when several declarations share a name in the same scope, the compiler combines them into a single definition. It’s the reason interfaces are described as open. The same mechanism lets you add a property to Window for a script tag you load yourself, or add a field to a library’s request type.

Merging interfaces

The basic rule is simple. Members from every declaration end up in one interface:

interface Settings {
  theme: "light" | "dark";
}

interface Settings {
  fontSize: number;
}

const s: Settings = { theme: "dark", fontSize: 14 }; // needs both

Two rules decide what happens when members overlap.

Properties must agree. A non-function member that appears in both halves must have exactly the same type:

interface Settings {
  theme: string;
}
// Error: Subsequent property declarations must have the same type.
//   Property 'theme' must be of type '"light" | "dark"', but here has type 'string'.

Methods become overloads. A function member with the same name is allowed, and each declaration contributes signatures to one overloaded method:

interface Parser {
  parse(input: string): string;
}

interface Parser {
  parse(input: Uint8Array): string;
}

declare const p: Parser;
p.parse("x");              // fine
p.parse(new Uint8Array()); // fine

The later declaration’s overloads are placed before the earlier ones. That matters because overloads are tried in order, as covered in function overloads. The handbook notes one exception: signatures with a single string-literal parameter type get moved to the top.

Merging with namespaces

A namespace is TypeScript’s older way of grouping values under a name, covered in namespaces, the legacy module system. Namespaces merge with each other, and more usefully, with functions, classes and enums. Only exported members of a namespace are visible after the merge.

A function that also carries properties is a common JavaScript pattern. Merging a namespace into it types that pattern:

function greet(name: string) {
  return `${greet.prefix}, ${name}`;
}

namespace greet {
  export const prefix = "Hello";
}

A namespace merged into a class can add static-style values and nested types:

class Album {
  constructor(public title: string) {}
}

namespace Album {
  export const maxTracks = 30;
  export interface Track { title: string }
}

const track: Album.Track = { title: "Intro" };

Enums merge with namespaces the same way, which lets you hang helper functions like Color.parse off an enum. Enums with the same name can also merge with each other. When merging with a function or class, the namespace must come after it. One caveat: namespaces that contain values generate JavaScript, so they’re rejected under the erasableSyntaxOnly flag that Node’s type stripping relies on.

Merging a class with an interface

class Widget {}

interface Widget {
  render(): string;
}

const w = new Widget();
w.render(); // type-checks, then throws at runtime

The interface adds render to Widget’s instance type, and nothing checks that the class provides it. This is deliberate, because it’s how mixin libraries tell the compiler about methods they attach at runtime. In ordinary code, though, it’s a quiet way to lie to the type checker. If you want the compiler to verify the class, use class Widget implements Renderable with a differently named interface.

Why type aliases can’t merge

type Config = { debug: boolean };
type Config = { verbose: boolean };
// Error: Duplicate identifier 'Config'.

Think of an interface as a sign-up sheet on a noticeboard: anyone in scope can add a line, and the compiler reads the whole sheet. A type alias is a label on a sealed box. type Config = ... binds one name to one type expression, finished the moment it’s written. There’s no member list to append to, and the expression on the right might not be an object at all. It could be a union or a conditional type, where “adding a property” has no meaning.

That’s also the practical argument in type aliases vs interfaces. If you never want a type to be reopened, an alias guarantees it. If you’re publishing a type that consumers should be able to extend, an interface allows it.

Adding to types declared in another module or in the global scope uses declare module and declare global. Those are covered in writing declaration files and module augmentation.

About the video

Matt Pocock’s two-minute video shows the use of declaration merging you’re most likely to meet in real code: reopening a global interface with declare global so that the compiler learns about something your app adds at runtime, and getting better inference everywhere as a result. It’s one application, not a survey. Interface merging rules, namespace merging with functions, classes and enums, the class-and-interface trap, and why aliases can’t merge are all carried by the text above, and declare global itself gets fuller treatment in writing declaration files and module augmentation. For a slower, example-by-example walkthrough of interface, enum and namespace merging, Navin Balla’s course excerpt is in the links.

Check yourself

  1. 01One file declares `interface Settings { theme: "light" | "dark" }` and another part of the same scope declares `interface Settings { theme: string }`. What does TypeScript say?

    It reports `Subsequent property declarations must have the same type`, because both declarations name the non-function property `theme` with different types. Merging only combines members; it won't pick one of two conflicting property types.

  2. 02Why does declaring `interface Parser { parse(input: string): string }` and then `interface Parser { parse(input: Uint8Array): string }` not produce an error?

    Function members are allowed to repeat. The two `parse` signatures become overloads of a single method, so a `Parser` accepts either a string or a `Uint8Array`. The later declaration's signatures are listed first in the merged overload set.

  3. 03Why is merging a class with an interface of the same name riskier than ordinary interface merging?

    The interface's members are added to the class's instance type, so the compiler believes every instance has them. Nothing checks that the class body actually implements or initialises those members, so a call can type-check and still fail at runtime with a `TypeError` saying the method is not a function.

  4. 04What's the underlying reason a `type` alias can't be reopened the way an interface can?

    An alias is just a name for a type expression that is complete when written; there is nothing to append to. An interface declares a named object type whose member list the compiler collects from every declaration with that name, so additional declarations have somewhere to go.

  5. 05What are the two everyday reasons you'd rely on interface merging deliberately?

    To add members to a type someone else declared, such as a global interface like `Window` or an interface exported by a library, and to describe JavaScript patterns where one name is used as both a value and a set of attached properties or types. The first case is done with `declare global` and module augmentation, covered in a later lesson.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark