Global augmentation lets you add new things to existing global types or modules. It helps you customize or extend code without changing original files.
0
0
Global augmentation in Typescript
Introduction
You want to add new properties to built-in types like Window or Document.
You need to add extra types to a third-party library without editing its code.
You want to add global helper functions or variables with types.
You want to fix or improve types from external packages.
You want to share common types across many files without importing.
Syntax
Typescript
declare global {
interface ExistingGlobalInterface {
newProperty: string;
}
}
export {}You must use declare global inside a module (a file with at least one import or export).
Always add export {} at the end to make the file a module.
Examples
This adds a new number property
myCustomValue to the global Window object.Typescript
declare global {
interface Window {
myCustomValue: number;
}
}
export {}This adds a new method
first() to all arrays to get the first item safely.Typescript
declare global {
interface Array<T> {
first(): T | undefined;
}
}
Array.prototype.first = function() {
return this.length > 0 ? this[0] : undefined;
};
export {}This adds a new global variable
myGlobalFlag with boolean type.Typescript
declare global {
var myGlobalFlag: boolean;
}
export {}Sample Program
This program adds a new property appVersion to the global window object and then prints it.
Typescript
declare global {
interface Window {
appVersion: string;
}
}
window.appVersion = "1.0.3";
console.log(`App version is ${window.appVersion}`);
export {}OutputSuccess
Important Notes
Global augmentation only works inside modules, so add export {} if needed.
Be careful not to overwrite existing types or properties accidentally.
Use global augmentation to improve type safety and avoid modifying original library code.
Summary
Global augmentation lets you add or change types on global objects or modules.
Use declare global inside a module to do this safely.
This helps customize or fix types without changing original code files.