苗条打字稿上的苗条自定义事件

Svelte custom event on svelte typescript

我在我的 svelte-typescript 项目上使用 clickOutside 指令,当我将自定义事件分配给相关元素时出现此错误

Type '{ class: string; onclick_outside: () => boolean; }' is not assignable to type 'HTMLProps<HTMLDivElement>'.
  Property 'onclick_outside' does not exist on type 'HTMLProps<HTMLDivElement>'

这是我的代码片段

{#if profileToolbar}
<div
    transition:fly={{ y: -20, duration: 300 }}
    use:clickOutside={profileToolbarContainer}
    on:click_outside={() => (profileToolbar = !profileToolbar)}
    class="origin-top-right absolute right-0 mt-2 w-48 rounded-md
    shadow-lg z-10 shadow-md">

这是我目前使用的 clickOutside 指令 https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7

我是打字稿的新手,所以我真的不知道从哪里开始 google 搜索,有人知道如何解决这个问题吗?感谢您的帮助

根据 doc,您可以在项目的某处创建一个 .d.ts 文件。并在该文件中放入以下内容:

declare namespace svelte.JSX {
  interface HTMLAttributes<T> {
    onclick_outside: () => void
  }
}

请阅读文档了解更多详情。

这个声明对我有用

declare namespace svelte.JSX {
  interface DOMAttributes<T> {
    onclick_outside?: CompositionEventHandler<T>;
  }
}

不要忘记在 tsconfig.json

中指定自定义类型声明的位置

好的,现有答案对我来说只是部分有用。鉴于 clickOutside 操作触发了一个名为 click_outside 的自定义事件,我得出以下解决方案:

declare namespace svelte.JSX {
    interface HTMLProps<T> {
        onclick_outside?: (e: CustomEvent) => void;
    }
}