Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

yup typescript type error of optional object member

I want to define a yup schema for object, containing inner object property which is optional;

type Inner = {
  size: number;
  price: number;
};

type Container = {
  inner?: Inner;
};

const containerSchema: yup.SchemaOf<Container> = yup.object().shape({
  inner: yup
    .object({
      size: yup.number().defined(),
      price: yup.number().defined(),
    })
    .optional(),
});

For some reason I get a quite misleading typescript error:

const containerSchema: ObjectSchemaOf<Container, never>
Type 'ObjectSchema<Assign<ObjectShape, { inner: OptionalObjectSchema<{ size: DefinedNumberSchema<number | undefined, AnyObject>; price: DefinedNumberSchema<number | undefined, AnyObject>; }, AnyObject, TypeOfShape<...>>; }>, AnyObject, TypeOfShape<...>, AssertsShape<...>>' is not assignable to type 'ObjectSchemaOf<Container, never>'.
  Type 'Assign<ObjectShape, { inner: OptionalObjectSchema<{ size: DefinedNumberSchema<number | undefined, AnyObject>; price: DefinedNumberSchema<number | undefined, AnyObject>; }, AnyObject, TypeOfShape<...>>; }>' is not assignable to type '{ inner: BaseSchema<Maybe<Inner | undefined>, AnyObject, Inner | undefined>; }'.
    The types of 'inner.__inputType.size' are incompatible between these types.
      Type 'number | undefined' is not assignable to type 'number'.
        Type 'undefined' is not assignable to type 'number'.ts(2322)

Typescript error disappears if I make inner property required by removing question mark.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to define the object inside object like this:

type Inner = {
  size: number;
  price: number;
};

type Container = {
  inner?: Inner;
};

const containerSchema: yup.SchemaOf<Container> = yup.object().shape({
  inner: yup.object().shape({
    size: yup.number().defined(),
    price: yup.number().defined(),
  }).optional()
});

You require to use .object().shape(). See How I can validate object inside objects in yup?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading