Home > other >  Yup Infertype doesn't work for optional fields
Yup Infertype doesn't work for optional fields

Time:08-10

Hi yup's Infertype doesn't work properly for optional fields.

const userSchema = yup.object({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email().optional().notRequired(),
  website: yup.string().url().nullable(),
  createdOn: yup.date().default(() => new Date()),
});

Expected type:

/* {
  name: string;
  age: number;
  email?: string | undefined
  website?: string | null | undefined
  createdOn: Date
}*/

Here is my type:

enter image description here

Email and website fields are should be optional.

tsconfig.json:

  "compilerOptions": {
    ...
    "strict": true,
    "strictNullChecks": true
  }

CodePudding user response:

In the current version of Yup we have solved it using Yup.SchemaOf<Type>:

type User = {
  name: string
  age: number
  email?: string
  website?: string | null
  createdOn: Date
}


const userSchema: Yup.SchemaOf<User> = object({
  name: string().required(),
  age: number().required().positive().integer(),
  email: string().email(),
  website: string().url().nullable(),
  createdOn: date().default(() => new Date()),
});

In upcoming versions of Yup you can use InferType:

import { object, string, string, date, InferType } from 'yup';

const userSchema = object({
  name: string().required(),
  age: number().required().positive().integer(),
  email: string().email(),
  website: string().url().nullable(),
  createdOn: date().default(() => new Date()),
});

type User = InferType<typeof userSchema>;
/* {
  name: string;
  age: number;
  email?: string | undefined
  website?: string | null | undefined
  createdOn: Date
}*/
  • Related