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

后端 未结 23 2781
青春惊慌失措
青春惊慌失措 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:39

    First you need to declare the window object in current scope.
    Because typescript would like to know the type of the object.
    Since window object is defined somewhere else you can not redefine it.
    But you can declare it as follows:-

    declare var window: any;
    

    This will not redefine the window object or it will not create another variable with name window.
    This means window is defined somewhere else and you are just referencing it in current scope.

    Then you can refer to your MyNamespace object simply by:-

    window.MyNamespace
    

    Or you can set the new property on window object simply by:-

    window.MyNamespace = MyObject
    

    And now the typescript won't complain.

提交回复
热议问题