Using Yup with defined nested Typescript types

24 views Asked by At

I'm using Yup with Typescript and getting a typescript error when creating the Yup schema.

type Data = {
  enabled: boolean;
  schedule: Schedule;
};

type Schedule = {
  unit: "day" | "month" | "week",
  quantity: number
};

const validation: Yup.ObjectSchema<Data> = Yup.object({
  enabled: Yup.boolean().required(),
  schedule: Yup.object<Schedule>({
    quantity: Yup.number().min(1).required(),
    unit: Yup.string().oneOf(["day", "week", "month"]).required(),
  }).required()
}).required();

The tsc error:

Type 'ObjectSchema<{ enabled: boolean; schedule: object; }, object>' is not assignable to type 'ObjectSchema<Data, object>'.
  The types of 'fields.schedule' are incompatible between these types.
    Type 'Schema<object, object>' is not assignable to type 'Schema<Schedule, object>'.
      Type 'object' is not assignable to type 'Schedule'.

I realize this is coming from the schedule type. I can't use Yup's inferType becase I don't have strict null checking enabled (which I believe is required according to the Yup readme)

0

There are 0 answers