Declaration Merging
Declaration Merging — the core idea
TypeScript can merge certain declarations with the same name, especially interfaces. This lets separately maintained declarations contribute members to a common interface. The merging must remain consistent, and it creates no runtime object by itself.
What you’ll learn
- Explain declaration merging with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The two interface declarations merge into a single Settings shape requiring both theme and volume. The JavaScript contains only the preferences object and its read operation.
Keep the boundary clear: Type aliases do not merge the same way; repeating `type Settings = ...` is a duplicate declaration error.
See the idea as a flow
Run the complete TypeScript example
Save the code as declaration-merging.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
interface Settings { theme: string }
interface Settings { volume: number }
const preferences: Settings = { theme: "dark", volume: 50 };
console.log(`${preferences.theme}:${preferences.volume}`);Verified output
dark:50Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable declaration-merging.ts; run: node declaration-merging.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The two interface declarations merge into a single Settings shape requiring both theme and volume. The JavaScript contains only the preferences object and its read operation.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Type aliases do not merge the same way; repeating type Settings = ... is a duplicate declaration error.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Add a third Settings interface with language:string and update preferences to match.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
TypeScript can merge certain declarations with the same name, especially interfaces.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.