Hello-World
Hello-World

Reputation: 82

Svelte typescript error for event Listener

Following this tutorial, I am trying to replicate the same in typescript.

export function pannable(node: Node) {
    let x: number;
    let y: number;
    function handleMousedown(event: MouseEvent) {
        x = event.clientX;
        y = event.clientY;
        node.dispatchEvent(
            new CustomEvent('panstart', {
                detail: { x, y }
            })
        );
        window.addEventListener('mousemove', handleMousemove);
        window.addEventListener('mouseup', handleMouseup);
    }

   // ...

    node.addEventListener('mousedown', handleMousedown);

I get this error:

Argument of type '(event:MouseEvent) =>void' is not assignable to parameter of type 'EventListnerOrEventListenerObject | null'.
      Type '(event:MouseEvent) =>void' is not assignable to type 'EventListner'. 
        Types of parameters 'event' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent': altKey, button, buttons, clientX and, 21 more.

I could fix this by changing event:MouseEvent to event:Event in the function definition. But then I get-

Property clientX does not exist on type 'Event'.
Property clientY does not exist on type 'Event'.

What should be the correct types?

Upvotes: 0

Views: 855

Answers (2)

femanzo
femanzo

Reputation: 179

Just adding to the answer, you also need to declare the custom event types in a .d.ts file, for example, you can use the app.d.ts provided by the sveltekit and place this code:

declare namespace svelte.JSX {
    export interface HTMLAttributes {
        onpanmove?: (event: CustomEvent) => void
        onpanend?: (event: CustomEvent) => void
        onpanstart?: (event: CustomEvent) => void
    }
}

And change the

export function pannable(node: Node) {

to

export function pannable(node: HTMLElement) {

Upvotes: 1

brunnerh
brunnerh

Reputation: 184376

The problem is Node, that is too basic a type. It does not have type definitions for the given events.

Use HTMLElement instead.

Upvotes: 1

Related Questions