流类型-声明签名,声明未知类型的属性接触中缺少预期的键/值类型

时间:2020-06-30 14:51:07

标签: javascript reactjs flowtype

我在输入事件时遇到问题。如果我这样做:

function(e: MouseEvent | TouchEvent) {
   const coords = e.touches ? e.touches[0].clientX : e.clientX
}

我收到此错误

 1. Cannot get e.clientX because property clientX is missing in TouchEvent
 2. Cannot get e.touches[0] because an index signature declaring the expected key / value type is
missing in property touches of unknown type 

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在流程中,检查对象类型的方法不是验证某个属性是否存在,因为这并不总是听起来正确。相反,您想使用instanceof

我对您的函数进行了一些更改,以便它返回,但它应该是您想要的。

function getClientX(e: MouseEvent | TouchEvent): number {
  if (e instanceof TouchEvent) {
    return e.touches[0].clientX;
  }
  return e.clientX;
}
相关问题