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:
typealiases (TS2300 Duplicate identifier) and classes with classes - Class + interface merging is unsafe: the interface adds members the class never implements, with no error;
implementsis 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.