nino.porcino nino.porcino - 3 months ago 9
TypeScript Question

how to promote a module to global in typescript?

I have a library contained in a module that I use very often, so I want to promote it as "global" and use without requiring it.

In pure JavaScript it's easy as

window.mylib = require("mylib")


but I'm finding it difficult to do in TypeScript because apparently you can't mix "module" and "ambient" code. So this doesn't work:

import MyLib = require("mylib");
window.mylib = MyLib;
interface Window {
mylib: mylib;
}


because the Window interface is augmented only for one file.

Is there a way to do that (that doesn't include generating a custom mylib.d.ts) ?

Answer

You should do something like:

yourModule.ts

import MyLib = require("mylib"); 

export {};

declare global {
    interface Window {
        mylib: mylib;
    }
}

window.mylib = MyLib; 

And then you just import it when needed:

import "./yourModule";

It's shorty discussed in Global augmentation.