Skip to the solution
MediumFrontend10 min read

What is declaration merging?

813 views

The problem

Question presented to candidate: "TypeScript lets you write interface User twice and ends up with one type. What is declaration merging, which kinds of declarations can merge with which, and when is it useful or dangerous?"

What a strong answer should cover:

  • Declaration merging: the compiler combines several declarations with the same name (in the same scope) into one definition
  • Interface + interface: members are combined; a non-function member declared twice must have the identical type (TS2717); methods become overloads, with later declarations' signatures first and single-string-literal signatures bubbled to the top
  • Namespace merges with a function, class or enum (static members, nested types, helpers), and must come after the function or class (TS2434); enums merge with enums
  • What does not merge: type aliases (TS2300 Duplicate identifier) and classes with classes
  • Class + interface merging is unsafe: the interface adds members the class never implements, with no error; implements is the checked alternative
  • Real uses: extending global or library interfaces (Window, a library's options interface), which is the basis of module augmentation

Code / implementation expected: Optional β€” two interface declarations merging, and a function or class merged with a namespace.

  • interface-merging

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptThe merges that work
TypeScriptWhat does not merge, and the unsafe class + interface merge

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 29 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is the difference between void, undefined and never as return types?

Continue