bhylu.com

Advertisements

TypeScript Declaration Merging

Compatible declarations with the same mergeable name can contribute members to one type. Interfaces support this; type aliases do not reopen in the same way.

How it works

Two declarations extend a desk settings contract in this controlled example. The final value must satisfy both required properties. Merging is useful for library extension points and module augmentation, but surprising global merges can hide where a property came from. Keep extensions in a deliberate module or declaration boundary and document which package contract is being augmented.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

interface DeskSettings { desk: string }
interface DeskSettings { limit: number }
const settings: DeskSettings = { desk: "East", limit: 5 };
console.log(settings.desk, settings.limit);

Expected result

East 5

The resulting interface has desk and limit. Conflicting declarations of the same property are not a way to override its type arbitrarily. Module augmentation also cannot manufacture runtime behavior: the library must really provide the members that the augmented types promise.