Handling Events in TS - No overload

Viewed 1967

I have the _onClick function, which listens to click or touch events depending on the device, so my event is MouseEvent or TouchEvent type.

In useEffect, addEventListener complains with the message: No overload matches this call (2769).

How can I properly write this down to avoid TS error?

const _onClick = (e: MouseEvent & TouchEvent):void => {
  e.preventDefault();

  const positionX = (e.touches && e.touches[0].pageX) || e.clientX;
};


useEffect(() => {
  if (tablet) {
    document.addEventListener('touchstart', _onClick);
  }
    document.addEventListener('mousedown', _onClick);
  }
}, []);
1 Answers

Since e can be either MouseEvent or TouchEvent you shoudl use a union type (|) not an intersection type (&). An intersection type would mean e were MouseEvent and TouchEvent at the same time.

To differentiate between the two cases (and access specific properties to each type) you can use an in type guard:


const _onClick = (e: MouseEvent | TouchEvent): void => {
    e.preventDefault();

    const positionX = 'touches' in e ? e.touches[0].pageX : e.clientX;
};

declare const tablet: boolean;
if (tablet) {
    document.addEventListener('touchstart', _onClick);
} else {
    document.addEventListener('mousedown', _onClick);
}

Play

Related