How to extend the 'Window' typescript interface

前端 未结 2 801
你的背包
你的背包 2020-12-29 03:20

In my example, I\'m trying to extend the TS Window interface to include a polyfill for fetch. Why doesn\'t matter. The question is \"how do I tell T

相关标签:
2条回答
  • 2020-12-29 03:25

    You need the declare global

    declare global {
      interface Window {
        fetch:(url: string, options?: {}) => Promise<any>
      }
    }
    

    This works then:

    window.fetch('/blah').then(...); 
    
    0 讨论(0)
  • 2020-12-29 03:47

    When you have a top-level import or export in your file (which you must somewhere to be having this problem), your file is an external module.

    In an external module, declaring an interface always creates a new type rather than augmenting an existing global interface. This mimics the general behavior of module loaders -- that things declared in this file don't merge or interfere with things in the global scope.

    The reason for this gyration is that otherwise there wouldn't be a way to, in an external module, define new variables or types with the same name as those in the global scope.

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