1

I have a custom event handler function as follows

/** Dispatch event on click outside of node */
export function eventHandlers(node: HTMLElement) {
  
    const handleClick = (event: MouseEvent) => {
        if (node && !node.contains(event.target as Node)) {
            node.dispatchEvent(
                new CustomEvent('click_outside')
            )
            
        }
    };

    document.addEventListener('click', handleClick, true);
  
    return {
        destroy() {
            document.removeEventListener('click', handleClick, true);
        }
    }
}

When I tried to use it in the HTML (svelte) as follows it throws an error:

Argument of type { class: string; "on:click_outside": (event: MouseEvent) => void; } is not assignable to parameter of type Omit<Omit<HTMLLiAttributes, "pattern" | "style" | "title" | "cite" | "data" | "form" | "label" | "slot" | "span" | "summary" | "id" | "class" | "accesskey" | ... 300 more

The html is as follows (svelte)

    function handleClickOutside(event) {
        alert('Click outside!');
    }


<h1>Hello {name}!</h1>
<div use:clickOutside on:click_outside={handleClickOutside}>
    Click outside me!
</div>

What does this mean and how can i resolve this?

Dai
  • 141,631
  • 28
  • 261
  • 374
jeff
  • 910
  • 2
  • 6
  • 25
  • 1
    Does this answer your question? [Svelte (svelte-kit) type custom action event with typescript](https://stackoverflow.com/questions/73025100/svelte-svelte-kit-type-custom-action-event-with-typescript) - You have to declare custom events if you are using TypeScript... – H.B. Nov 05 '22 at 10:38

1 Answers1

2

Add this declaration to your app.d.ts file:

declare namespace svelteHTML {
    interface HTMLAttributes<T> {
        'on:click_outside'?: CompositionEventHandler<T>
    }
}

TypeScript needs to know that this custom event handler is valid.