module-augmentation
Use Module Augmentation to Improve Types
Overview
Module augmentation allows you to add declarations to existing modules, including third-party libraries. This is useful when a library's types are incomplete or when you're extending a library with plugins. Use declare module to add properties, methods, or types to existing modules.
When to Use This Skill
- Extending third-party types
- Adding properties to existing interfaces
- Plugins that extend core types
- Declaration merging needed
- Augmenting global types
The Iron Rule
Use module augmentation to add to existing types. Declare the same module name and add your declarations.
Example
// Adding to an existing module
// types/vue.d.ts
declare module 'vue' {
export interface ComponentCustomProperties {
$myProperty: string;
$myMethod(): void;
}
}
// Now Vue components have these properties
// this.$myProperty works with type safety
// Augmenting global types
declare global {
interface Window {
myLib: MyLibrary;
}
}
// Now window.myLib is typed
Reference
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 71: Use Module Augmentation to Improve Types
More from marius-townhouse/effective-typescript-skills
exhaustiveness-checking
Use when handling tagged unions. Use when adding new cases to discriminated unions. Use when switch statements must cover all cases.
13code-gen-independent
Use when confused about types at runtime. Use when trying to use instanceof with interfaces. Use when type errors don't prevent JavaScript output.
12tsconfig-options
Use when setting up a TypeScript project. Use when confused by type checking behavior. Use when strict mode causes unexpected errors.
11exclusive-or-properties
Use when exactly one of several properties should be present. Use when modeling mutually exclusive options. Use when building component props with alternative configurations. Use when designing API parameters that have variants.
11module-by-module-migration
Use when migrating large codebases. Use when converting JavaScript to TypeScript. Use when managing dependencies. Use when planning migration order. Use when teams are adopting TypeScript.
11editor-interrogation
Use when debugging type inference. Use when types behave unexpectedly. Use when learning unfamiliar code.
11