我创建了一个可复制的示例
我的问题是:如何使用react-final-form
修复此打字脚本错误
错误为:
Type '{ name: string; onBlur: (event?: FocusEvent<HTMLElement>) => void; onChange: (event: any) => void; onFocus: (event?: FocusEvent<HTMLElement>) => void; type?: string; value: T; checked?: boolean; multiple?: boolean; }' is not assignable to type 'T'.
'{ name: string; onBlur: (event?: FocusEvent<HTMLElement>) => void; onChange: (event: any) => void; onFocus: (event?: FocusEvent<HTMLElement>) => void; type?: string; value: T; checked?: boolean; multiple?: boolean; }' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint '{}'.
单击上面的链接,您可以很容易地看到它
我看到了这个很好的答案,但我不知道如何将其应用于这个案例。
它似乎在抱怨ComponentType不一定具有您试图应用于Component对象的FieldRenderProps中的属性。您需要编写类型,以便它了解您的组件将始终具有这些属性。
import React, { ComponentType, FC } from 'react';
import { FieldRenderProps, FieldInputProps } from 'react-final-form'
type ComponentBaseProps<T> = FieldInputProps<T> & Record<string, any>
const createAdapter = <T, >(Component: ComponentType<ComponentBaseProps<T>>) => {
return ({ input, meta, ...rest }: FieldRenderProps<T>): JSX.Element => {
return <Component {...input} {...rest} />
}
}
以上类型将通知typescript,您提供的组件具有您试图分配的所有属性,所有组成您的属性:
- 输入变量(FieldInputProps类型(
- rest变量(类型为Record<string,any>(
需要注意的另一件事是ComponentType的泛型参数是应用于组件的完整属性集,而FieldRenderProps的泛型参数则是表单数据的类型。将T直接用于这两种情况是导致您不匹配的原因。