是的,对象不可分配,但为什么呢?

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

从这段代码:

import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

interface IFormInputs {
    firstName: string; 
}

const validationSchema = Yup.object({
    firstName: Yup.string().required(), 
});

const Form = () => {
    const { register, handleSubmit, formState: { errors } } = useForm<IFormInputs>({
        resolver: yupResolver(validationSchema),
    });

    const onSubmit = (data: IFormInputs) => {
        console.log(data);
    };

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input {...register('firstName')} />
            <p>{errors.firstName?.message}</p>
            <input type="submit" />
        </form>
    );
};

export default Form;

解析器:

错误
  Types of parameters 'options' and 'options' are incompatible.
    Type 'ResolverOptions<IFormInputs>' is not assignable to type 'ResolverOptions<AssertsShape<{ firstName: unknown; }>>'.
      Type 'IFormInputs' is not assignable to type 'AssertsShape<{ firstName: unknown; }>'.ts(2322)
form.d.ts(64, 5): The expected type comes from property 'resolver' which is declared here on type 'Partial<{ mode: keyof ValidationMode; reValidateMode: "onBlur" | "onChange" | "onSubmit"; defaultValues: AsyncDefaultValues<IFormInputs> | { ...; }; ... 9 more ...; delayError: number; }>'
,

yupResolver 中的validationSchema 错误:

  Type 'ObjectSchema<{ firstName: string; }, AnyObject, { firstName: undefined; }, "">' is missing the following properties from type 'ObjectSchema<{ firstName: unknown; }, AnyObject, TypeOfShape<{ firstName: unknown; }>, AssertsShape<{ firstName: unknown; }>>': getDefaultFromShape, __inputType, _isPresentts(2345)
,

,
javascript typescript yup
1个回答
0
投票

对我有用的解决方案是我忘记添加 Yup 模式的形状。例如。

const schema = Yup.object<SomeInterface>().shape({
firstName: "first name here",
lastName: "last name here"
});
const { register, handleSubmit, formState: { errors }} = useForm({ resolver: yupResolver(schema) });
© www.soinside.com 2019 - 2024. All rights reserved.