Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Does not exist on type string?

The "Property does not exist on type String" error occurs when we try to access a property that does not exist on the string type. To solve the error, use an object instead of a string, or make sure you're accessing a valid built-in method on the string.

Does not exist on type never?

The error "Property does not exist on type 'never'" occurs when we forget to type a state array or don't type the return value of the useRef hook. To solve the error, use a generic to explicitly type the state array or the ref value in your React application.


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'))


There are a few ways to solve this problem:

Somethings exemples:

1-) Do it a cast:

(Windows as any).X

2-) Put the follow code in file react-app-env.d.ts

interface Window {
X?: {
  Y?: {
      .......
   }
}

}


you can solve the problem easily without any need to declaration

window["FB"]

I use this without declare global

declare const window: Window &
   typeof globalThis & {
     FB: any
   }