Declaration Merging
Declaration Merging
π¨βπΌ One unique feature of interfaces is declaration mergingβyou can declare
the same interface multiple times, and TypeScript merges them together.
interface User {
name: string
}
interface User {
email: string
}
interface User {
age: number
}
// User now has name, email, AND age!
const user: User = {
name: 'Alice',
email: 'alice@example.com',
age: 30,
}
This is impossible with type aliasesβyou'd get a "duplicate identifier" error.
Declaration Merging Across Modules
π¦ Declaration merging also works across different files! When you use
declare global, you can augment interfaces from other modules.// config.ts β must be a module (has an import or export)
declare global {
interface Config {
appName: string
}
}
// theme-config.ts β also a module
declare global {
interface Config {
theme: 'light' | 'dark'
}
}
// main.ts
import './config.ts'
import './theme-config.ts'
// Now Config has both appName AND theme!
const config: Config = {
appName: 'MyApp',
theme: 'dark',
}
The
declare global syntax creates a global interface that can be augmented
from any file. When you import both files, TypeScript merges all the Config
declarations into a single interface!About imports and exports: We haven't covered modules in detail yet, but
here's what you need to know:
import './file.ts'- Imports a file to run its side effects / activate mergesexport { name }- Exports a value so other files can use it- A
.tsfile is a module when it has at least one top-levelimportorexport. Augmentation files must be modules so they can be imported; if you have nothing else to export, an empty export is enough to mark the file as a module. declare global- Creates or augments global types that can be merged across files
For this exercise, you'll import the augment file to activate the declaration
merge. Don't worry about understanding all the detailsβwe'll cover modules
properly later!
π¨ Open
and
:
- In
index.ts, usedeclare globalto declareConfigwithappName: string - In
config-augment.ts, usedeclare globalto augmentConfigwiththeme: 'light' | 'dark'andmaxConnections: number, and make the file a module so it can be imported - In
index.ts, side-effect import./config-augment.tsto activate the merge - Create a
configobject with all merged properties (appName,theme,maxConnections) - Implement
getTheme(config: Config)that returnsconfig.theme - Export
configandgetThemeby name
Completion criteria
- Named exports:
config,getTheme config.appNameis a string;config.themeis'light'or'dark';config.maxConnectionsis a numbergetTheme(config)returns that theme valueconfig-augment.tsis importable as a module