jquense / yup

Dead simple Object schema validation
MIT License
22.87k stars 932 forks source link

How to implemention Cicular Dependency of Schema? #1996

Closed wacanam closed 1 year ago

wacanam commented 1 year ago

Let me describe the situation.

We have Schema A and Schema B.

Schema A is an object which it has a property that map to Schema B Schema B is also an object which it has a property that map to Schema A

now here is the error message from TS. image The property that I mean is the nurses.

here code snippets:

export const appointmentSchema = yup.object({ // for single appointment
    id: yup.number().required(),
    title: yup.string().nullable(),
    complaint: yup.string().nullable(),
    bookingDate: yup.string().nullable(),
    appointmentType: yup.number().nullable(),
    status: yup.string().nullable(),
    consentAgreed: yup.boolean().nullable(),
    isActive: yup.boolean().optional(),
    isDeleted: yup.boolean().optional(),
    accountId: yup.number().nullable(),
    offeredServiceId: yup.number().nullable(),
    departmentId: yup.number().nullable(),
    bookingTypeId: yup.number().nullable(),
    systemCategoryId: yup.number().nullable(),
    statuses: yup.array().of(appointmentStatusSchema).nullable(),
    nurses: yup.array().of(nurseAppointmentSchema).nullable(),
});
export const nurseAppointmentSchema = yup.object({
    id: yup.number().required("Nurse appointment id is required"),
    nurseId: yup.number().required("Nurse id is required"),
    remarks: yup.string().required("Remarks is required"),
    status: yup.string().required("Status is required"),
    accountName: yup.string().required("Account name is required"),
    appointmentId: yup.number().required("Appointment id is required"),
    bookingDate: yup.string().required("Booking date is required"),
    dateCreated: yup.string().required("Date created is required"),
    dateUpdated: yup.string().required("Date updated is required"),
    appointment: yup.lazy(() => appointmentSchema),
});

I don't want to create separate schemas with the same property to maximize code reusability.

jquense commented 1 year ago

You should use lazy for recursive schema. You might also need to add explicit type annotations to satisfy TS, there isn't much yup can do about that