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

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

    For reference (this is the correct answer):

    Inside a .d.ts definition file

    type MyGlobalFunctionType = (name: string) => void
    

    If you work in the browser, you add members to the browser's window context by reopening Window's interface:

    interface Window {
      myGlobalFunction: MyGlobalFunctionType
    }
    

    Same idea for NodeJS:

    declare module NodeJS {
      interface Global {
        myGlobalFunction: MyGlobalFunctionType
      }
    }
    

    Now you declare the root variable (that will actually live on window or global)

    declare const myGlobalFunction: MyGlobalFunctionType;
    

    Then in a regular .ts file, but imported as side-effect, you actually implement it:

    global/* or window */.myGlobalFunction = function (name: string) {
      console.log("Hey !", name);
    };
    

    And finally use it elsewhere in the codebase, with either:

    global/* or window */.myGlobalFunction("Kevin");
    
    myGlobalFunction("Kevin");
    

提交回复
热议问题