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 merges
  • export { name } - Exports a value so other files can use it
  • A .ts file is a module when it has at least one top-level import or export. 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
index.ts
and
config-augment.ts
:
  1. In index.ts, use declare global to declare Config with appName: string
  2. In config-augment.ts, use declare global to augment Config with theme: 'light' | 'dark' and maxConnections: number, and make the file a module so it can be imported
  3. In index.ts, side-effect import ./config-augment.ts to activate the merge
  4. Create a config object with all merged properties (appName, theme, maxConnections)
  5. Implement getTheme(config: Config) that returns config.theme
  6. Export config and getTheme by name

Completion criteria

  • Named exports: config, getTheme
  • config.appName is a string; config.theme is 'light' or 'dark'; config.maxConnections is a number
  • getTheme(config) returns that theme value
  • config-augment.ts is importable as a module

Please set the playground first

Loading "Declaration Merging"
Loading "Declaration Merging"
Login to get access to the exclusive discord channel.
Loading Discord Posts