Svelte中非标准窗口事件的TypeScript键入

问题描述

我在Svcode中将svelte与TypeScript一起使用,并且在vscode中安装了svelte扩展名。

在我的App.svelte中,

<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} />

您可以看到,在<svelte:window>标记中,我正在使用on:beforeinstallprompt事件,这是与在某些浏览器(例如Chrome)中运行的渐进式Web应用程序相关的非标准事件。不幸的是,但可以理解的是,有效的TypeScript声明在beforeinstallprompt对象的定义中没有Window。 (TypeScript声明很可能来自svelte vscode扩展名。)

我的问题是vscode在on:beforeinstallprompt显示错误,因为它认为该事件不存在。

错误消息是:

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)

要摆脱该错误消息,我尝试添加一个*.d.ts文件来扩展需要扩展的内容,但是我没有发现要扩展的内容(例如接口)或完成方法

(注意:我知道可以使用onMount()将处理程序附加到window.beforeinstallprompt事件的选项,但我想知道它如何/是否与<svelte:window>一起工作。)

解决方法

将其放入您的d.ts文件中:

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

然后确保d.ts中引用了tsconfig.json文件。如果它读取的内容类似于"include": ["src/**/*"],并且您的d.ts文件位于src内部,则它应该可以工作。您可能需要重新加载才能使更改生效。

文档: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