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

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

    For those who want to set a computed or dynamic property on the window object, you'll find that not possible with the declare global method. To clarify for this use case

    window[DynamicObject.key] // Element implicitly has an 'any' type because type Window has no index signature
    

    You might attempt to do something like this

    declare global {
      interface Window {
        [DyanmicObject.key]: string; // error RIP
      }
    }
    

    The above will error though. This is because in Typescript, interfaces do not play well with computed properties and will throw an error like

    A computed property name in an interface must directly refer to a built-in symbol
    

    To get around this, you can go with the suggest of casting window to so you can do

    (window as any)[DynamicObject.key]
    

提交回复
热议问题