[typescript] How do you explicitly set a new property on `window` in TypeScript?

Most of the other answers are not perfect.

  • Some of them just suppress the type inference for show.
  • Some of the others only care about global variables as namespaces, but not as interfaces/classes

I also encounter the similar problem this morning. I tried so many "solutions" on StackOverflow, but none of them produced absolutely no type errors and enabled triggering type jumping in IDE(webstorm or vscode).

Finally, from here

https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512

I found a reasonable solution to attach typings for a global variable that acts as interface/class and namespace both.

Example is below:

// typings.d.ts
declare interface Window {
    myNamespace?: MyNamespace & typeof MyNamespace
}

declare interface MyNamespace {
    somemethod?()
}

declare namespace MyNamespace {
    // ...
}

The code above merges the typings of namespace MyNamespace and interface MyNamespace into the global variable myNamespace(the property of window).