简体   繁体   中英

TypeScript typing of non-standard window event in Svelte

I'm using Svelte with TypeScript in vscode and I have the Svelte extension installed in vscode.

In my App.svelte I have

<script lang="ts">
  // a bunch of code that isn't relevant. This should just show that 
  // `lang="ts"` is set (above)
</script>

// here comes the crucial part
<svelte:window on:beforeinstallprompt={functionDeclaredInTheScript} />

As you can see, in the <svelte:window> tag I'm using the on:beforeinstallprompt event which is a non-standard event related to progressive web apps that works in some browsers (ie Chrome). Unfortunately but understandably, the TypeScript declarations that are active don't have beforeinstallprompt on the definition of the Window object. (The TypeScript declarations are most likely the ones coming from the Svelte vscode extension.)

The problem I have is that vscode shows an error at on:beforeinstallprompt because it thinks that the event does not exist.

The error message is:

Type '{ onbeforeinstallprompt: (e: any) => void; }' is not assignable to type 'HTMLProps<Window> & SvelteWindowProps'.
Property 'onbeforeinstallprompt' does not exist on type 'HTMLProps<Window> & SvelteWindowProps'.ts(2322)

To get rid of the error message I've tried adding a *.d.ts file to extend what needs to be extended but I haven't found out what to extend (eg an interface) or how that's done.

(Note: I'm aware of the option to use onMount() to attach the handler to the window.beforeinstallprompt event but I want to know how/if it works with <svelte:window> .)

Put this in your d.ts file:

declare namespace svelte.JSX {
  interface HTMLAttributes<T> {
    // You can replace any with something more specific if you like
    onbeforeinstallprompt?: (event: any) => any;
  }
}

Then make sure that d.ts file is referenced in your tsconfig.json . If it reads something like "include": ["src/**/*"] and your d.ts file is inside src , it should work. You may need to reload for the changes to take effect.

Docs: https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#im-using-an-attributeevent-on-a-dom-element-and-it-throws-a-type-error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM