TypeScript error: Property 'X' does not exist on type 'Window'

后端 未结 1 449
北海茫月
北海茫月 2020-12-18 17:20

I have added TS to my React/Redux app.

I use window object in my app like this:

componentDidMount() {
  let FB = window.FB;
}

相关标签:
1条回答
  • 2020-12-18 18:10

    Why does declare const window: any; work?

    Because you declare a local variable of type any. Having something of type any essentially turns off type checking for window so you can do anything with it. I really do not recommend this solution, it is a really bad one.

    Why doesn't type Window = { FB: any } work? You define a type Window. This type if defined in a module has nothing to do with the type of the global window object, it is just a type that happens to be called Window inside your module.

    The good solution To extend window you must extend the global Window interface. You can do this like this:

    declare global {
        interface Window {
            FB:any;
        }
    }
    
    let FB = window.FB; // ok now
    

    Note that this extension is going to be available in your whole project not just the file you define it in. Also if FB has definitions you might consider typing it a bit better (FB: typeof import('FBOrWhateverModuleNameThisHas'))

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