0

The following is my function


export function clickOutside(node: HTMLElement) {
    const handleClick = (event: MouseEvent) => {
        if (!node.contains(event.target as Node)) {
            node.dispatchEvent(new CustomEvent('outclick'));
        }
    };

    document.addEventListener('click', handleClick, true);

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


I use this as following

<div class="modal" use:clickOutside on:outclick={() => {showModal = false}}>
  {#if showModal}
    <SignIn />
  
  {/if}
</div>

I get an error saying Argument of type '{ class: string; "on:outclick": () => void; }' is not assignable to parameter of type 'Omit<Omit<HTMLAttributes. But the code works alright. I guess it could be the typescript related error.

How can I solve this?

jeff
  • 910
  • 2
  • 6
  • 25
  • The error you're seeing is related to TypeScript and is caused by the fact that TypeScript does not recognize the outclick event that you're dispatching on the node element. To fix this, you can add a type definition for the outclick event using the CustomEventInit interface. – Ersin Demirtas Feb 15 '23 at 20:49
  • 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) – H.B. Feb 15 '23 at 21:39
  • 1
    The comment from @H.B. is, probably, orders of magnitude superior but I just want to offer what I've done instead which I'm quite happy with. I've declared the action like `export function clickOutside(node: HTMLElement, callback: (evt: MouseEvent) => void): ActionReturn<(evt: MouseEvent) => void> { ... }` then, instead of dispatching the event, you can just call `callback(event)`. Finally, on the caller, you can do `
    showModal = true} ...>`
    – carlosV2 Feb 16 '23 at 01:59
  • @carlosV2. It worked. Thank you. But I have encountered another error which I will post as different question – jeff Feb 16 '23 at 11:33
  • Nice! Would you be happy if I post it as an answer? – carlosV2 Feb 16 '23 at 12:40

0 Answers0