From ec2210b045b6a7d954e2840c1d93e9975066b3ea Mon Sep 17 00:00:00 2001 From: ShipItAndPray Date: Thu, 9 Apr 2026 11:45:42 -0500 Subject: [PATCH] docs: explain declare global in declaration reference --- .../copy/en/declaration-files/By Example.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/documentation/copy/en/declaration-files/By Example.md b/packages/documentation/copy/en/declaration-files/By Example.md index 6717d697f834..c8bf44bc86c1 100644 --- a/packages/documentation/copy/en/declaration-files/By Example.md +++ b/packages/documentation/copy/en/declaration-files/By Example.md @@ -249,3 +249,35 @@ Use `declare function` to declare functions. declare function greet(greeting: string): void; ``` +## Global augmentation with `declare global` + +_Documentation_ + +> The `magic-string-time` module adds a `startsWithHello()` method to every string when it is imported. + +_Code_ + +```ts +import "magic-string-time"; + +"hello world".startsWithHello(); +``` + +_Declaration_ + +If a library is imported but adds types to the global scope, put those declarations inside `declare global {}`. +This is how you describe global-modifying modules and other cases where module code augments existing global types. + +```ts +export {}; + +declare global { + interface String { + startsWithHello(): boolean; + } +} +``` + +`declare global` only works from inside a module, so the declaration file needs at least one `import` or `export`. +If the file already has an `import` or `export`, you can remove the `export {}` line. +For more about how global augmentation works, see [Declaration Merging](/docs/handbook/declaration-merging.html#global-augmentation) and the [global-modifying module template](/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html).