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

后端 未结 23 2151
青春惊慌失措
青春惊慌失措 2020-11-22 03:53

I setup global namespaces for my objects by explicitly setting a property on window.

window.MyNamespace = window.MyNamespace || {};
23条回答
  •  囚心锁ツ
    2020-11-22 04:35

    Most of the other answers are not perfect.

    • Some of them just suppress the type inference for shop.
    • Some of the others only cares about global variable as namespace, but not as interface/class

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

    Finally, from here

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

    , I find a reasonable solution to attach typings for global variable which 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 {
        // ...
    }
    

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

提交回复
热议问题