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

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

    Here's how to do it, if you're using TypeScript Definition Manager!

    npm install typings --global
    

    Create typings/custom/window.d.ts:

    interface Window {
      MyNamespace: any;
    }
    
    declare var window: Window;
    

    Install your custom typing:

    typings install file:typings/custom/window.d.ts --save --global
    

    Done, use it‌! Typescript won't complain anymore:

    window.MyNamespace = window.MyNamespace || {};
    
    0 讨论(0)
  • 2020-11-22 04:29

    Using TSX? None of the other answers were working for me.

    Here's what I did:

    (window as any).MyNamespace
    
    0 讨论(0)
  • 2020-11-22 04:29

    Create a file called global.d.ts e.g /src/@types/global.d.ts then define an interface like:

    interface Window {
      myLib: any
    }
    

    ref: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html

    0 讨论(0)
  • 2020-11-22 04:31

    I don't need to do this very often, the only case I have had was when using Redux Devtools with middleware.

    I simply did:

    const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    

    Or you could do:

    let myWindow = window as any;

    and then myWindow.myProp = 'my value';

    0 讨论(0)
  • 2020-11-22 04:31

    After finding answers around, I think this page might be helpful. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation Not sure about the history of declaration merging, but it explains why the following could work.

    declare global {
        interface Window { MyNamespace: any; }
    }
    
    window.MyNamespace = window.MyNamespace || {};
    
    0 讨论(0)
  • 2020-11-22 04:31

    I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.

    In order for my library to use declarations I had to use the d.ts extention for the file that declares the new properties of the global object.

    So in the end, the file ended up with something like:

    /path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts

    Once created, don't forget to expose it in your public_api.ts.

    That did it for me. Hope this helps.

    0 讨论(0)
提交回复
热议问题