typescript抛出类型'keyboardEvent | focusevent<HTMLInputElement, Element>'不能分配“focusevent<HTMLInputElement, Element>”。?

问题描述 投票:0回答:1

I具有以下类型和可重复使用的

FormContextInput
组件,如下所示:
Input

组件接受一个功能。我在两个不同的组件
export type FormContextInput = { name:string, eventType: "onBlur" | "onKeyDown" | "onClick", validate: (event:React.FocusEvent<HTMLInputElement> | KeyboardEvent) => void | Promise<void>, } & React.InputHTMLAttributes<HTMLInputElement>;

Input
中重复使用它。
validate
触发器在
A
上的验证函数,以及
B
的验证触发器触发
A
onBlur
代码:
B

onKeyDown
验证功能:

Input

export default function Input({name, eventType, validate, ...props}:FormContextInput) {

  async function handleValidate(event:React.FocusEvent<HTMLInputElement> | KeyboardEvent) {
    try {
      await Promise.resolve(validate(event));
      setError("");
    } catch (error) {
      setError((error as Error).message);
    }

  }

  return (
      <input name={name} {...props}
      {...(eventType === "onBlur" && {onBlur:handleValidate})}
      {...(eventType === "onKeyDown" && {onKeyDown:handleValidate})}
      />
  )
}
验证功能:

A

但是我在所有组件上都会遇到三个错误。

function validation(event: React.FocusEvent<HTMLInputElement>) {}

B
有一个错误行,我将其验证功能传递给the tos:
function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {}

错误:

A
B
错误:
Input

each他们中的一个正在抱怨另一个事件的类型,在我看来,打字稿忽略了两种类型之间的
A

,而不将它们识别为单独的事物!


Type '(event: FocusEvent<HTMLInputElement, Element>) => void' is not assignable to type '(event: FocusEvent<HTMLInputElement, Element> | KeyboardEvent) => void | Promise<void>'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'FocusEvent<HTMLInputElement, Element> | KeyboardEvent' is not assignable to type 'FocusEvent<HTMLInputElement, Element>'.
      Type 'KeyboardEvent' is missing the following properties from type 'FocusEvent<HTMLInputElement, Element>': relatedTarget, nativeEvent, isDefaultPrevented, isPropagationStopped, persist
错误行在

B

标签下方:

Type '(event: KeyboardEvent<HTMLInputElement>) => void' is not assignable to type '(event: FocusEvent<HTMLInputElement, Element> | KeyboardEvent) => void | Promise<void>'. Types of parameters 'event' and 'event' are incompatible. Type 'FocusEvent<HTMLInputElement, Element> | KeyboardEvent' is not assignable to type 'KeyboardEvent<HTMLInputElement>'. Type 'FocusEvent<HTMLInputElement, Element>' is missing the following properties from type 'KeyboardEvent<HTMLInputElement>': altKey, charCode, ctrlKey, code, and 11 more


i我试图将类型定义更改为
|

,但由于它太松了,因此也会引发错误,我必须缩小事件类型。 “修复”此操作的唯一解决方案是使用

Input

,但这也存在问题。
    

问题是Typescript期望

<input/>
函数可以同时处理
No overload matches this call.

React.SyntheticEvent
reactjs typescript next.js react-typescript
1个回答
0
投票

Solution:


使用
any
中的类型防护
validate

通过缩小事件类型来解决类型冲突。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.