对 MouseEvent 和 TouchEvent 接口的 React Typescript 事件类型

React Typescript event type for both interfaces MouseEvent and TouchEvent

我正在尝试编写一个函数来处理 mousetouch 事件。通过组合接口 React.TouchEventReact.MouseEvent, 喜欢:

onStart = (event: React.TouchEvent | React.MouseEvent) => {
    event.persist();
    console.log('event ', event);
    if (event.touches) {
        console.log(event.touches);
    }
    if (event.screenX) {
        console.log(event.screenX);
    }
};

日志给了我预期的输出,我没有收到任何控制台错误,它按我预期的方式运行。但是我的编辑器出现错误:

Error:(94, 22) TS2339: Property 'screenX' does not exist on type 'MouseEvent | TouchEvent'. Property 'screenX' does not exist on type 'TouchEvent'.

Error:(90, 13) TS2339: Property 'touches' does not exist on type 'MouseEvent | TouchEvent'. Property 'touches' does not exist on type 'MouseEvent'.

我怎样才能同时使用接口 React.TouchEventReact.MouseEvent 而不会出现所有这些错误?

通过检查条件中的 instanceof TouchEventinstanceof MouseEvent 并使用 event 中的 nativeEvent 属性,可以访问每个单独的接口没有错误。

onStart = (event: React.TouchEvent | React.MouseEvent) => {
    event.persist();
    console.log('event ', event);
    if (event.nativeEvent instanceof TouchEvent) {
        console.log(event.nativeEvent.touches);
    }

    if (event.nativeEvent instanceof MouseEvent) {
        console.log(event.nativeEvent.screenX);
    }
};

我会使用 type predicates 的 TypeScript。代码更具可读性。

例如

import React, { Component } from 'react';

function isTouchEvent(e: React.TouchEvent | React.MouseEvent): e is React.TouchEvent {
  return e && 'touches' in e;
}

function isMouseEvent(e: React.TouchEvent | React.MouseEvent): e is React.MouseEvent {
  return e && 'screenX' in e;
}

export default class MyComponent extends Component {
  onStart = (event: React.TouchEvent | React.MouseEvent) => {
    event.persist();
    if (isTouchEvent(event)) {
      console.log(event.touches);
    }
    if (isMouseEvent(event)) {
      console.log(event.screenX);
    }
  };

  render() {
    return <div>my component</div>;
  }
}