Typescript - Global Declaration - How to declare a global variable
Table of Contents
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.
Example
Global Augmentation inside a module
On a window object
declare global {
interface Window { jQuery: any; }
}
- Others…
// Declare global constant
declare global {
interface Window {
ezConsentCategories:any;
__ezconsent: any;
}
}
Others
declare var page: String;
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> {}
}
global library definition
Support
Missing import statement
you can either turn off the inspection (Inspection profile | JavaScript | Node.js | Missing require() statement)