React useForm结合yup验证时errors类型报错求助
React Hook Form + Yup 类型错误解决:
errors.password?.message 类型不兼容 问题场景
使用React Hook Form结合Yup做表单验证时,代码实际运行正常,但VSCode中errors.password?.message出现TypeScript类型错误,构建阶段也会抛出该报错。
相关代码:
Yup Schema 与 Hook 初始化
const schema = yup.object().shape({ password: yup.string().required(), confirm_password: yup.string().required(), }); const { register, handleSubmit, formState: { errors }, reset, } = useForm({ resolver: yupResolver(schema) });
表单渲染代码
<div> <Form.Control {...register('password')} name="password" type="password" placeholder="Enter New Password" /> </div> <div className="is-flex-rowss"> <small className="text-danger">{errors.password?.message}</small> </div>
错误提示
Merge<FieldError, FieldErrorsImpl<DeepRequired>> | undefined Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired>> | undefined' is not assignable to type 'ReactNode'. Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired>>' is not assignable to type 'ReactNode'. Type 'Merge<FieldError, FieldErrorsImpl<DeepRequired>>' is missing the following properties from type 'ReactPortal': key, children, type, propsts(2322) index.d.ts(1373, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes, HTMLElement>'
解决方案
方案1:给useForm显式指定泛型类型(推荐)
定义表单字段的类型接口,传递给useForm,让TypeScript精准推断errors的结构:
// 定义表单值的类型 type FormValues = { password: string; confirm_password: string; }; // 初始化useForm时指定泛型 const { register, handleSubmit, formState: { errors }, reset, } = useForm<FormValues>({ resolver: yupResolver(schema) });
方案2:类型断言
直接将message断言为string | undefined,明确告诉TS它的实际类型:
<small className="text-danger">{errors.password?.message as string | undefined}</small>
方案3:空值合并运算符兜底
确保即使message不存在时返回空字符串(ReactNode可接受的合法类型):
<small className="text-danger">{errors.password?.message ?? ''}</small>
原因说明
未给useForm指定泛型时,TypeScript无法准确推断表单字段的结构,导致errors.password的类型被模糊处理为嵌套错误对象或单个错误的合并类型,进而认为message可能不是合法的ReactNode。显式指定泛型后,TS能明确每个字段的错误类型,消除类型歧义。
内容的提问来源于stack exchange,提问作者adviner
相关产品推荐
相关产品推荐

