npm yup 1.0.0-beta.5
v1.0.0-beta.5 - partial fixes and cast migration path

latest releases: 1.4.0, 1.3.3, 1.3.2...
21 months ago

Beta 5 fixes partial and deepPartial making it work correctly with lazy schema. Specifically the optionality is added after lazy is evaluated but before any other when conditions are added. This makes it consistent with other conditional schema, where runtime conditions always supersede previous schema configuration. This allows for optional overrides if necessary.

const person = object({
  name: string().required(),
  age: number().required(),
  legalGuardian:  string().when('age', {
    is: (age) => age != null && age < 18,
    then: (schema) => schema.required(),
  }),
});

const optionalPerson = person.partial()

person.cast({name: 'James', age: 6 }) // => TypeError legalGuardian required

// age is still required b/c it's applied after the `partial`
optionalPerson.cast({name: 'James',  age: 6 }) // => TypeError legalGuardian required

This works slightly differently for lazy which have no schema to "start" with:

const config = object({
  nameOrIdNumber:  lazy((value) => {
     if (typeof value === 'number') return number().required()
     return string().required()
  }),
});

const opti = config.partial()

config.cast({}) // => TypeError nameOrIdNumber is required

config.partial().cast({}) // => {}

Cast optionality migration path

A larger breaking change in v1 is the assertion of optionality during cast, making previous patterns like string().nullable().required() no longer possible. Generally this pattern is used when deserialized data is not valid to start, but will become valid through user input such as with an HTML form. v1 no longer allows this, but in order to make migration easier we've added an option to cast that mimics the previous behavior (not exactly but closely).

const name = string().required()

name.cast(null, { assert: 'ignore-optionality'}) // => null

We recommend updating your schema to new patterns where possible but this allows for incremental upgrades

What's Changed

New Contributors

Full Changelog: v1.0.0-beta.4...v1.0.0-beta.5

Don't miss a new yup release

NewReleases is sending notifications on new releases.