A. Duff A. Duff - 2 months ago 16
TypeScript Question

List of globals in Typescript

Is it possible to configure the Typescript compiler to recognize certain symbols as global variables?

For example, right now you can tell the compiler that a symbol exists in your code with:

declare var MY_GLOBAL: number;


But if you need to use this variable in many different files, it would be better if you could let Typescript know about it in
tsconfig.json
so you wouldn't have to have this line in every single file that uses this variable. Is this possible?

Answer

This is already the behavior in files which are not modules (those which lack top-level imports or exports). The easiest thing to do is to make a non-module file and put the declaration there. But if your file is a module and you want to declare something in the global scope, and you are using TypeScript 2.0 or later, you can use declare global:

declare global {
    var MY_GLOBAL: number;
}