43

What is "declare global" and how is it possible ? I found this code inside Lodash typings. The problem is that when I try to replicate this into my.d.ts file exactly since global is not a namespace, module, function or var, I'm not allowed to do it. So question is how this declaration is possible in Typescript.

PS So maybe there are some additional compiler options which will allow this?

declare global {
    interface Set<T> { }
}
Hivaga
  • 3,738
  • 4
  • 23
  • 36

1 Answers1

61

This is not dependent on compiler settings. declare global is used inside a file that has import or export to declare things in the global scope. This is necessary in files that contain import or export since such files are considered modules, and anything declared in a module is in the module scope.

Using declare global in a file that is not a module (that is contains no import/export) is an error since everything in such a file is in the global scope anyway.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • 11
    Yes, I have learned these principles through practice, but is there any official document to explain them? – John Hou Feb 27 '20 at 03:30
  • 4
    @JohnHou As of now, there is https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation as well as https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html – Mörre Apr 23 '21 at 21:46