Why do developers use module augmentation in TypeScript?
Think about how you can extend existing code safely without changing the original files.
Module augmentation lets you add new types or properties to existing modules. This is useful when you want to extend functionality or add typings for third-party libraries without changing their code.
What is the output of this TypeScript code using module augmentation?
declare module 'math-lib' { export function multiply(x: number, y: number): number; } // Augmenting the module declare module 'math-lib' { export function square(x: number): number; } // Implementation const mathLib = { multiply: (x: number, y: number) => x * y, square: (x: number) => x * x }; console.log(mathLib.multiply(3, 4)); console.log(mathLib.square(5));
Check how the augmented function square is defined and used.
The module is first declared with multiply. Then it is augmented to add square. Both functions exist in mathLib. So multiply(3,4) is 12 and square(5) is 25.
What error does this TypeScript code produce?
declare module 'string-utils' { export function capitalize(s: string): string; } // Incorrect augmentation declare module 'string-utils' { export const capitalize: (s: string) => string; } const utils = { capitalize: (s: string) => s.charAt(0).toUpperCase() + s.slice(1) }; console.log(utils.capitalize('hello'));
Look at how capitalize is declared in both module declarations.
The first declaration exports a function named capitalize. The second tries to export a constant with the same name, causing a duplicate identifier error.
Which option shows the correct syntax to augment a module named my-lib by adding a new interface User?
Remember the keyword to declare module augmentation and the quotes around module name.
The correct syntax uses declare module 'module-name' with quotes around the module name. Options B, C, and D have syntax errors or missing quotes.
You want to add a new method formatDate to a third-party library's module date-lib without changing its source code. Why is module augmentation the best approach?
Think about how to extend functionality without risking breaking the original library.
Module augmentation lets you add new types or methods to existing modules without modifying their source code. This keeps the original library intact and compatible with updates.