TypeScriptModules and namespaces
Namespace declaration merging in TypeScript
9 Declaration merging: one namespace declared twice
hardDeclare a namespace holding an interface and a function. Declare the same namespace again with a second interface and function. Show that TypeScript merges the two and both are usable.
Stuck? Three hints, smallest first
- 1. Two blocks with the same namespace name merge into one. Interfaces with the same name merge too.
- 2. This is how a library adds to something you already have without editing it.
- 3. The merge is checked: two declarations that disagree about a member’s type are an error, not a silent overwrite.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// First declaration.
namespace UI {
export interface Button {
label: string;
}
export function createButton(label: string): Button {
return { label };
}
}
// Second declaration, same name. TypeScript merges them into one namespace.
namespace UI {
export interface Panel {
title: string;
buttons: Button[]; // the sibling from the first block is in scope
}
export function createPanel(title: string, labels: string[]): Panel {
return { title, buttons: labels.map((l) => createButton(l)) };
}
}
// A third block, adding a member to the EXISTING Button interface.
// Interfaces of the same name merge as well, so Button now has two fields.
namespace UI {
export interface Button {
disabled?: boolean;
}
}
const button = UI.createButton('Book now');
const panel = UI.createPanel('Seats', ['1A', '1B', '2A']);
// The merged field is available on the same interface.
const disabledButton: UI.Button = { label: 'Sold out', disabled: true };
console.log(button);
console.log(panel.title, 'has', panel.buttons.length, 'buttons');
console.log(panel.buttons.map((b) => b.label).join(', '));
console.log('merged field:', disabledButton.disabled);
test('the first block still works', button.label, 'Book now');
test('the second block sees the first', panel.buttons.length, 3);
test('panel title', panel.title, 'Seats');
test('button labels', panel.buttons.map((b) => b.label), ['1A', '1B', '2A']);
test('the third block added a field to Button', disabledButton.disabled, true);
test('and that field is optional, so old code is fine', UI.createButton('x').disabled, undefined);
Output
Two merges are happening. The three namespace UI blocks merge into one namespace, and the two interface Button declarations merge into one interface with both fields. The last assertion shows why the new field is optional: making it required would have broken createButton, which does not set it. This is exactly the mechanism used to add types to a library you do not control.