【问题标题】:TypeScript typing of non-standard window event in SvelteSvelte 中非标准窗口事件的 TypeScript 类型
【发布时间】:2020-12-28 01:13:31
【问题描述】:

我在 vscode 中使用带有 TypeScript 的 Svelte,并且我在 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} />

如您所见,在&lt;svelte:window&gt; 标记中,我使用了on:beforeinstallprompt 事件,这是一个与可在某些浏览器(即Chrome)中运行的渐进式网络应用程序相关的非标准事件。不幸但可以理解的是,处于活动状态的 TypeScript 声明在 Window 对象的定义上没有 beforeinstallprompt。 (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 事件的选项,但我想知道它如何/是否与&lt;svelte:window&gt; 一起使用。)

【问题讨论】:

    标签: typescript visual-studio-code progressive-web-apps svelte svelte-3


    【解决方案1】:

    把它放在你的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

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 1970-01-01
      • 2018-02-18
      • 2021-01-11
      • 2010-12-28
      • 2023-01-29
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多