Skip to content

Commit ec2210b

Browse files
committed
docs: explain declare global in declaration reference
1 parent 119f931 commit ec2210b

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

packages/documentation/copy/en/declaration-files/By Example.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,35 @@ Use `declare function` to declare functions.
249249
declare function greet(greeting: string): void;
250250
```
251251

252+
## Global augmentation with `declare global`
253+
254+
_Documentation_
255+
256+
> The `magic-string-time` module adds a `startsWithHello()` method to every string when it is imported.
257+
258+
_Code_
259+
260+
```ts
261+
import "magic-string-time";
262+
263+
"hello world".startsWithHello();
264+
```
265+
266+
_Declaration_
267+
268+
If a library is imported but adds types to the global scope, put those declarations inside `declare global {}`.
269+
This is how you describe global-modifying modules and other cases where module code augments existing global types.
270+
271+
```ts
272+
export {};
273+
274+
declare global {
275+
interface String {
276+
startsWithHello(): boolean;
277+
}
278+
}
279+
```
280+
281+
`declare global` only works from inside a module, so the declaration file needs at least one `import` or `export`.
282+
If the file already has an `import` or `export`, you can remove the `export {}` line.
283+
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).

0 commit comments

Comments
 (0)