Svelte / SvelteKit and Typescript: add properties to the window object, or extend the interface

Viewed 1435

I have the following working (running) code but am getting the TypeScript error Property 'onSubmit' does not exist on type 'Window & typeof globalThis'..

function onSubmit() {
  . . .
}

onMount(() => {
  window.onSubmit = onSubmit; <-- Error
});

onDestroy(() => {
  window.onSubmit = null; <-- Error
});

In my global.d.ts file I have tried exporting an interface to import

export interface CustomWindow extends Window {
  onSubmit: () => void;
}

and declaring a global

declare global {
  interface Window {
    onSubmit: () => void;
  }
}

Neither solution has been successful, the error persists. How can we add properties to the window object for TypeScript to recognize?

1 Answers

Almost correct, declare is the correct keyword, you don't need to wrap it with global though.

The following adds it:

declare interface Window {
  onSubmit: () => void;
}

Also make sure you don't have any imports or exports in your global.d.ts as then it's no longer treated as an ambient module.

Related