Yup and Typescript Schema Interface for `Yup.lazy()`

Viewed 3618

im struggling to create a typescript interface for a yup schema (https://github.com/jquense/yup/blob/master/docs/typescript.md)

given the typescript interface:

interface TestInterface {
  name: string;
};

the following return type is valid:

const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.string().required()
});

but in my code i have Yup.lazy() being used, but im unable to find out how i should create an interface for the following:

const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.lazy(() => Yup.string().required())
});

the error i get is:

Type 'ObjectSchema<Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>, Record<...>, TypeOfShape<...>, AssertsShape<...>>' is not assignable to type 'ObjectSchemaOf<TestInterface>'.
  Type 'Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>' is not assignable to type '{ name: BaseSchema<string, AnyObject, string>; }'.
    Types of property 'name' are incompatible.
      Type 'Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>' is missing the following properties from type 'BaseSchema<string, AnyObject, string>': deps, tests, transforms, conditions, and 35 more.ts(2322)
1 Answers

Your example works as you'd like using Yup.ObjectSchema with the addition of requiring your object.

Be sure to add .required() onto your .shape or .object chain so that the fields of your schema are certain to exist from TypeScript's perspective. It is in essence acting as NonNullable<TestInterface>

//    ✅ happy type
const testSchema1: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
  name: Yup.string().required(),
}).required();

//    ✅ happy type
const testSchema2: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
  name: Yup.lazy(() => Yup.string().required())
}).required();

Note: Working with the current (as of this post) version 0.32.11. A runkit example in plain JS with stubbed out types can be seen [here]

Source: https://github.com/jquense/yup/#ensuring-a-schema-matches-an-existing-type

Related