Yup ValidationSchema Type with ObjectSchema Not Working
Asked Answered
P

2

6
  • yup 0.30.0
  • @types/yup 0.29.14

I'm trying to generate a reusable type definition for a Yup validationSchema by using ObjectSchema but I keep getting an error

Using an example from the Yup docs here https://github.com/jquense/yup#ensuring-a-schema-matches-an-existing-type

interface TestValidationSchema {
  title: string;
}

const validationSchema: Yup.ObjectSchema<TestValidationSchema> = Yup.object({
  title: Yup.string().required()
});

...

 return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={validationSchema}
    >
...

The error

Type 'ObjectSchema<Shape<object | undefined, { title: string; }>, object>' is not assignable to type 'ObjectSchema<TestValidationSchema, object>'.
  Types of property 'fields' are incompatible.
    Type '{ title: Schema<string, object>; } | undefined' is not assignable to type '{ title: Schema<string, object>; }'.
      Type 'undefined' is not assignable to type '{ title: Schema<string, object>; }'.

I tried bumping the version of Yup to 32.11 and got a different, but still confusing error that makes me think I'm just using ObjectSchema incorrectly

Type 'OptionalObjectSchema<{ title: RequiredStringSchema<string | undefined, AnyObject>; }, AnyObject, TypeOfShape<{ title: RequiredStringSchema<string | undefined, AnyObject>; }>>' is not assignable to type 'ObjectSchema<TestValidationSchema, AnyObject, TypeOfShape<TestValidationSchema>, AssertsShape<TestValidationSchema>>'.
  The types of 'fields.title' are incompatible between these types.
    Type 'RequiredStringSchema<string | undefined, AnyObject>' is not assignable to type 'string'.ts(2322)

Any help is appreciated.

UPDATE

I just inspected the type returned from the validationSchema above, and the below type works. I'm still wondering why the example in the Yup docs isn't working for me though

type ValidationSchema = Yup.ObjectSchema<{
  title: string;
} | undefined, object>
Persona answered 9/8, 2022 at 22:37 Comment(2)
Did you create a GitHub issue for them? I'm experiencing the same, let's take it to 'em :-)Viewfinder
Same problem. Any issue open? I'll hop on the train.Nigrescent
C
2

just update yup and @types/yup @types/yup 0.29.14 yup 0.32.11 works fine

Chockfull answered 17/10, 2022 at 7:55 Comment(1)
I had a similar phenomenon and a similar solution worked. Turns out my submodule was using the wrong version of yup. Fixing the version of yup in the submodule worked perfectly.Oneself
I
1

Required does not allow undefined or null. You apply this to the title successfully.

I think the problem is not with the title, but with Yup.object(...) which allows undefined. Try making it required() as well.

Read more regarding Yup.object() here: https://github.com/jquense/yup#object

Indiscriminate answered 5/3, 2023 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.