Module lessons (2/2)
Declarations and Merging
Type declaration files (with .d.ts extension) are used in TypeScript to describe the shape of existing JavaScript code without implementing any actual logic. They contain only type definitions, interfaces, and function signatures.
These files are essential when using third-party libraries written in pure JavaScript.
Declaration Merging
Declaration Merging is a behavior where the compiler merges two or more separate declarations declared with the same name into a single definition.
The most common case is interface merging:
interface User {
name: string;
}
interface User {
age: number;
}
// The resulting User interface has both name and age properties!
const student: User = {
name: 'Alice',
age: 23,
};If properties share the same name, they must be of the same type, otherwise TypeScript will report an error.
Modifying Global and External Modules
We can use declaration merging to extend interfaces defined in other modules or in the global scope.
For example, if we want to add a property to the browser's global window object:
declare global {
interface Window {
analyticsToken: string;
}
}By using declare global, we tell TypeScript that we are injecting a new signature into the existing global Window interface.
Try it yourself
Exercise 1: Basic Declaration Merging
In TypeScript, interfaces with the same name in the same scope are automatically merged. Declare an interface User with property name: string, then in a second block declare the same interface User adding the property age: number. Finally, declare a constant user of type User with appropriate values.
Show hint
Declare interface User twice, inserting the respective properties, and then assign the fields to the user object.
Solution available after 3 attempts
Exercise 2: Extending the Global Window Interface
Imagine you want to extend the global Window interface to add a custom property named config of type Record<string, string>. Write the correct declaration using declare global to merge the new property into the global Window interface.
Show hint
Use declare global { interface Window { config: Record<string, string>; } }.
Solution available after 3 attempts