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
declare global {
interface Config {
appName: string
}
}
// theme-config.ts
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 code (side effects)export { name }- Exports a value so other files can use itdeclare 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 declare theConfiginterface withappName - In
config-augment.ts, usedeclare globalto augmentConfigwiththemeandmaxConnections - In
index.ts, importconfig-augment.tsto activate the merge - Create a config object with all merged properties (appName, theme, maxConnections)