Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'declare global' in Typescript?

Tags:

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> { } } 
like image 800
Hivaga Avatar asked Jul 15 '19 12:07

Hivaga


People also ask

What is global declaration function?

4.7. Global Declarations. Subroutine and format declarations are global declarations. No matter where you place them, what they declare is global (it's local to a package, but packages are global to the program, so everything in a package is visible from anywhere).

How do you declare a global const variable in TypeScript?

#Declare a Global Variable Another approach is to declare a global variable using the declare var syntax. This way, we can let TypeScript know that it can expect to find a global variable with the given name and type: declare var __INITIAL_DATA__: InitialData; We can now access the __INITIAL_DATA__ variable directly …

What is global variable declaration?

The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.


1 Answers

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.

like image 141
Titian Cernicova-Dragomir Avatar answered Sep 24 '22 08:09

Titian Cernicova-Dragomir