What is declaration merging in TypeScript?
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).