QA
Intermediate LevelJavaScript & TypeScript

How does declaration merging work in TypeScript interfaces?

❓ Interview Prompt: Explain declaration merging for interfaces, namespaces, and extending global third-party library types.

Declaration Merging occurs when the TypeScript compiler automatically combines two or more separate declarations declared with the same name in the same scope into a single unified type definition.

Characteristics:

•
Interfaces: Properties from subsequent declarations merge into the original interface.
•
Namespaces: Merge with classes or functions to attach static methods.
•
Global Module Augmentation: Used to add custom properties to third-party or global interfaces (like Window or Express.Request).

Code Implementation Example

typescript
// Declaration 1
interface User {
  id: number;
  name: string;
}

// Declaration 2 (Same name in same scope -> MERGES!)
interface User {
  email: string;
}

const u: User = { id: 1, name: 'Alice', email: 'alice@example.com' };

// Augmenting Global Window object
declare global {
  interface Window {
    appVersion: string;
  }
}
window.appVersion = '2.4.0'; // ✅ Merged into global Window!
💡Automatic interface property merging and global Window object augmentation.
🎯 Interview Key Takeaway

Declaration merging allows extending existing interfaces across files, essential for augmenting global and library types.

#TypeScript#Declaration Merging#Augmentation#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?