我试图使用react-hook-form及其useFieldArray
钩子注册数组元素,我得到了这个TypeScript错误:Argument of type '
phases.${number}.name' is not assignable to parameter of type '"_id" | "name" | "description" | "phases" | "isPrivate" | "createdBy" | "phases.0" | "phases.0.name" | "phases.0.description" | "phases.0.order"'.
基本上它不能regconize,因为索引可以是不同于0的东西。
代码如下:
interface IPhaseTemplate {
_id: string;
name: string;
description: string;
phases: [
{
name: string;
description: string;
order: number;
}
];
isPrivate: boolean;
createdBy: string;
}
function CreateNew({ updateStep }: CreatePhaseTemplateProps) {
const {
register,
handleSubmit,
formState: { errors },
control,
} = useForm<IPhaseTemplate>({
defaultValues: data ?? {
name: "",
description: "",
isPrivate: false,
phases: [
{
name: "",
description: "",
order: 0,
},
],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: "phases",
});
return (
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
<Stack spacing={1} alignItems="center">
{fields.map((field, index) => (
<Card sx={{ m: 1 }} key={field.id}>
<CardContent>
<TextField
label="Name"
fullWidth
{...register(`phases.${index}.name` as const, {
required: "Name is required",
})}
error={!!errors.phases?.[index]?.name}
helperText={errors.phases?.[index]?.name?.message}
sx={{ mb: 1 }}
/>
<TextField
label="Description"
fullWidth
multiline
rows={4}
{...register(`phases.${index}.description` as const, {
required: "Description is required",
})}
error={!!errors.phases?.[index]?.description}
helperText={errors.phases?.[index]?.description?.message}
/>
</CardContent>
<CardActions>
<Button size="small" onClick={() => remove(index)}>
Remove
</Button>
</CardActions>
</Card>
))}
</Stack>
</Box>
);
}
错误出现在phases.${index}.name
as const部分和描述部分。 我试过在https://react-hook-form.com/api/usefieldarray/#main上使用钩子并使用
as const`输入register部分,但TypeScript仍然对我大喊大叫
1条答案
按热度按时间jdgnovmf1#
尝试定义您的界面如下: