What is declaration merging in TypeScript?
Why Interviewers Ask This
This is a classic screening question for TypeScript roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Declaration merging is TypeScript's behavior of combining multiple declarations with the same name into a single definition. It happens automatically when the TypeScript compiler encounters two or more declarations with the same name in the same scope. Interface merging: the most common case — declaring an interface twice merges the properties: interface Window { myProp: string; } interface Window { anotherProp: number; } — results in Window having both properties. This is how libraries (like @types/express) extend third-party interfaces. Namespace merging: namespaces with the same name are merged. Merging a namespace with a class/function/enum: allows adding static members to classes or attaching types to functions. Declaration merging does NOT work with type aliases — re-declaring a type alias with the same name is an error. This is a key reason to prefer interface for things that may need to be extended externally (like library types).
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your TypeScript experience.