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

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

    Global are "evil" :), i think the best way to have also the portability is:

    First you export the interface: (eg: ./custom.window.ts)

    export interface CustomWindow extends Window {
        customAttribute: any;
    }
    

    Second you import

    import {CustomWindow} from './custom.window.ts';
    

    Third cast global var window with CustomWindow

    declare let window: CustomWindow;
    

    In this way you don't have also red line in different IDE if you use with existent attributes of window object, so at the end try:

    window.customAttribute = 'works';
    window.location.href = '/works';
    

    Tested with Typescript 2.4.x and newest!

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

    If you are using Typescript 3.x, you may be able to omit the declare global part in the other answers and instead just use:

    interface Window {
      someValue: string
      another: boolean
    }
    

    This worked with me when using Typescript 3.3, WebPack and TSLint.

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

    To keep it dynamic, just use:

    (<any>window).MyNamespace
    
    0 讨论(0)
  • 2020-11-22 04:14

    For those using the Angular CLI it's straightforward:

    src/polyfills.ts

    declare global {
      interface Window {
        myCustomFn: () => void;
      }
    }
    

    my-custom-utils.ts

    window.myCustomFn = function () {
      ...
    };
    

    If you're using IntelliJ, you also needed to change the following setting in the IDE before your new polyfills pick up:

    > File 
    > Settings 
    > Languages & Frameworks 
    > TypeScript 
    > check 'Use TypeScript Service'.
    
    0 讨论(0)
  • 2020-11-22 04:14

    Typscript does not perform typecheck on string properties.

    window["newProperty"] = customObj;
    

    Ideally, the global variable scenario should be avoided. I use it sometimes to debug an object in browser console.

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

    Using create-react-app v3.3 I found the easiest way to achieve this was to extend the Window type in the auto-generated react-app-env.d.ts:

    interface Window {
        MyNamespace: any;
    }
    
    0 讨论(0)
提交回复
热议问题