TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Avoiding window as any

You can avoid type casts by defining globals in a d.ts file.

const myGlobal = (window as any).__MY_GLOBAL__
//    ^? const myGlobal: any ⛔️
// global.d.ts

declare global {
  interface Window {
    __MY_GLOBAL__: number
  }
}

export {} // Needed to augment global scope

// main.ts

const myGlobal = window.__MY_GLOBAL__
//    ^? const myGlobal: number ✅