Svelte custom event on svelte typescript

I’m using clickOutside directive on my svelte-typescript project and I’m getting this error when I assign custom event to the related element

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

here’s a snippet of my code

{#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">

this is the clickOutside directive that I’m using currently https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7

I’m new to typescript so I don’t really know where to start with my google search, anyone knows how to tackle this issue? thanks for your help

3 thoughts on “Svelte custom event on svelte typescript”

  1. According to the doc, you can create a .d.ts file in your project somewhere. And put inside that file the following:

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

    Please read the doc for more detail.


    But my personal opinion to the issue is, if you’re not familiar with typescript at this point, try not to use it with svelte. Or if you must, then don’t take this kind of warning/error seriously. Otherwise you’ll end up wrestling with the tool a lot, which costs you more time asking question like this one, as oppose to save time for you.

    I am quite fluent in typescript, yet I eventually give up the endeavor.

    Although the dev team has put quite some effort to enhance the toolchain, with all due respect, it’s still quite far away from optimal.

    I understand the difficulty of the problem, cus svelte is very flexible, exotic to some extend, quite the opposite to typescript which is rigid and strict, thus they don’t work well together by nature.

    Reply
  2. Ok, so existing answers did work only partly for me. Given that the clickOutside action fires a custom event named click_outside i arrive at following solution:

    declare namespace svelte.JSX {
        interface HTMLProps<T> {
            onclick_outside?: (e: CustomEvent) => void;
        }
    }
    
    Reply
  3. This declaration worked for me

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

    Don’t forget to specify the location of your custom type declarations in tsconfig.json

    Reply

Leave a Comment