Home > database >  yup typescript type error of optional object member
yup typescript type error of optional object member

Time:05-11

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.

CodePudding user response:

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?

  • Related