0
votes

I am creating a sectional form. Each section must have initial values, and a validation schema. To help the team develop in a consistent way, I want to make sure that each section looks like this:

interface Section {
  initialValues: { [key: string]: any };
  validationSchema: { [key: string]: Yup.AnySchema };
}

Is there a way to constrain initialValues and validationSchema so that they must contain the same keys?

I.e., this will work:

const section1: Section = {
  initialValues: {
    name: "",
    age: undefined // will be a number
  },
  validationSchema: {
    name: Yup.string().required(),
    age: Yup.number().required()
  }
}

Whereas this would break:

const section1: Section = {
  initialValues: {
    name: "",
    age: undefined // will be a number
  },
  validationSchema: {
    name: Yup.string().required(),
    height: Yup.number().required() // should error, as height does not exist on initialValues
    // error because we are missing the age property and its validation here
  }
}

Is there a way to accomplish such a constraint in typescript, without having to predefine the keys?

@CertainPerformance oops yes, thank you, fixed thatSeth Lutske