【问题标题】:Annotate a function type to accept either a React.MouseEvent parameter or to remain anonymous注释函数类型以接受 React.MouseEvent 参数或保持匿名
【发布时间】:2021-12-04 13:28:45
【问题描述】:

我正在重构一些代码,根据用户是否在下拉菜单中选择了“编辑”或“删除”选项,向用户显示对话框。

当我努力使对话框组件更通用时,我正在尝试使handleClose 事件处理程序成为() => void 类型或(event: React.MouseEvent<HTMLElement>) => void 类型。

为了实现这一点,我注释了handleClose 事件处理程序,以便它接受两者;目前看起来像这样handleClose: () => void | ((event: React.MouseEvent<HTMLElement>) => void);

很好 - 但我仍然收到一条令我困惑的神秘错误消息。

错误信息:

Type '(event: React.MouseEvent<HTMLElement>) => void' is not assignable to type '() => void | ((event: MouseEvent<HTMLElement, MouseEvent>) => void)'.ts(2322)
FolderEditView.tsx(13, 5): The expected type comes from property 'handleClose' which is declared here on type 'IntrinsicAttributes & IProps'
(JSX attribute) IProps.handleClose: () => void | ((event: MouseEvent<HTMLElement, MouseEvent>) => void)

我在分配两种可能的类型时哪里出错了?为什么错误消息似乎表明在FolderEditView.tsx(13, 5) 中我没有使用React.MouseEvent... 进行注释?错误消息并未反映我的代码中所写内容的真实性,因此很难诊断这里发生了什么。

谢谢

【问题讨论】:

    标签: reactjs typescript types mouseevent


    【解决方案1】:

    您可能希望根据错误消息执行此操作(按照建议添加第二个泛型类型参数):

    (event?: React.MouseEvent<HTMLElement, MouseEvent>) => void
    

    event?:表示参数可以为空,这里不需要创建函数联合

    Live Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      相关资源
      最近更新 更多