我在我的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
我是打字新手,所以我真的不知道从哪里开始我的谷歌搜索,有人知道如何解决这个问题吗?谢谢你的帮助
根据文档,您可以在项目中的某个位置创建.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;
}
}
更新7/23/23
新的SvelteKit需要这个:
这是我的src/app.d.ts
文件。
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}
declare namespace svelteHTML {
interface HTMLAttributes<T> {
'on:clickOutside'?: CompositionEventHandler<T>;
}
}
}
export { };
J
对我来说,以下操作奏效了:
declare namespace svelteHTML {
interface HTMLAttributes<T> {
"on:click_outside"?: CompositionEventHandler<T>;
}
}
在您的src/app.d.ts
中。
基于这个