我在下面的链接中有一个最小的可重复的问题示例:
import React, { useState } from 'react';
type InputValue = string[] | string;
interface InputProps<T extends InputValue> {
value: T;
}
// -------------------------------------------------------------------------------------------------
// TEXT INPUT
// -------------------------------------------------------------------------------------------------
const TextInput = ({ value = '' }: InputProps<string>): React.ReactElement => {
return <input value={value} />;
};
// -------------------------------------------------------------------------------------------------
// FORM FIELD
// -------------------------------------------------------------------------------------------------
interface FormFieldProps<T extends InputValue> {
render: (props: InputProps<T>) => React.ReactElement;
value: T;
}
const FormField = <T extends InputValue>({
render,
value,
}: FormFieldProps<T>): React.ReactElement => (
<div>
{render({ value })}
</div>
);
// -------------------------------------------------------------------------------------------------
// FORM
// -------------------------------------------------------------------------------------------------
interface FieldPropsReturn<T> {
value: T[keyof T];
}
interface UseFormReturn<T> {
fieldProps: (name: keyof T) => FieldPropsReturn<T>;
}
const useForm = <T extends object>(): UseFormReturn<T> => {
const [formData] = useState<T>({} as T);
const fieldProps = (name: keyof T): FieldPropsReturn<T> => ({
value: formData[name],
});
return {
fieldProps
};
};
// -------------------------------------------------------------------------------------------------
// INDEX
// -------------------------------------------------------------------------------------------------
interface IndexFormFields {
fruits: string[];
name: string;
}
const Index = (): React.ReactElement => {
const { fieldProps } = useForm<IndexFormFields>();
return (
<FormField
{...fieldProps('name')}
render={(props): React.ReactElement => <TextInput {...props} />}
/>
);
};
export default Index;
基本上,我正在构建一些表单助手,包括一个FormField
,用于呈现表单组件.我希望这FormField
个渲染函数从传递给fieldProps
的键推断出值类型,但目前它在TextInput
组件上返回以下错误:
Type '{ value: string | string[]; }' is not assignable to type 'InputProps<string>'.
Types of property 'value' are incompatible.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.
根据IndexFormFields
接口,对于FormField
,fieldProps
为"name"的渲染函数是否有任何方式可以传递string
的值类型,而对于fieldProps
为"fruits"的渲染函数是否可以传递string[]
的值类型?