Tag Archives: TypeScript

Troubleshooting of typescript extended global window error

Using the custom attribute on the global window, typescript will report that the attribute does not exist,

console.log(window.foo) // ❌ Property ‘foo’ does not exist on type 'Window & typeof globalThis'.ts(2339)

The user-defined variable needs to be extended to the global window. You can add a type file or a normal. TS file in the project, as long as it can be found within the configuration scope of tsconfig.json.

type.d.ts

declare global {
  interface Window {
   	foo: string;
  }
}

If the following error occurs during type extension:

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.ts(2669)

The following contents can be added to the type file to take the specified file as the template and eliminate the error.

+ export {};

declare global {
  interface Window {
    foo: string;
  }
}