typescript global.d.ts and augmenting Window interface with app specific globals

Does you typescript code need to reference some global variables on window.* ? 

  • e.g. const string = window.I18n.t()

Are you getting typescript compiler errors when you do reference these?


If so then the solution is probably a typescript global.d.ts file for your app.

You can add definitions for typescript Window in it like so

interface Window {
I18n: any;
some_global_key: string;
}

Window is a built in typescript type that types window. When you define your own Window interface and add your custom properties to it, these will be merged with typescripts built in Window interface (thanks to typescript declaration merging).

I put the global.d.ts file in the root of my app. Typescript automatically picks it up and errors disappeared.

Being explicit at a global level about all your globals is a better solution than scattering (window as any).I18n.t() all over the code (imo).


references

good article about various options for globals in typescript land

interesting article about extending Window interface




Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more