Typescript - Global Declaration - How to declare a global variable

1 - About

typescript has only knowledge of its own script on not of its environment.

If you use third library, you need to declare it globally.

2 - Example

2.1 - Global Augmentation inside a module

Doc, ref

On a window object


declare global {
    interface Window { jQuery: any; }
}

  • Others…

// Declare global constant
declare global {
    interface Window {
        ezConsentCategories:any;
        __ezconsent: any;
    }
}

2.2 - Others


declare var page: String;

2.3 - global-modifying module


import {Browser, Page} from "puppeteer";

declare global {
    /*~ Here, declare things that go in the global namespace, or augment
     *~ existing declarations in the global namespace
     */
    interface String {
        fancyFormat(opts: StringFormatOptions): string;
    }
    const browser: Browser;
    const page: Page;
}

* lodash


import _ from 'lodash'; 

declare global { 
    //Example global constant for libraries served via webpack externals. example webpack config:: externals: { _: 'lodash' }
    //This assumes lodash was already load in DOM for example in <head> via CDN link before main.js is loaded.
    const _: typeof _; 

    //example of custom types
    type JSONPrimitive = string | number | boolean | null;
    type JSONValue = JSONPrimitive | JSONObject | JSONArray;
    type JSONObject = { [member: string]: JSONValue };

    //example of custom interface
    interface JSONArray extends Array<JSONValue> {}
}

2.4 - global library definition

3 - Support

3.1 - Missing import statement

you can either turn off the inspection (Inspection profile | JavaScript | Node.js | Missing require() statement)


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap