Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript infers optional fields for Yup schema when using .required()

I am validating my create campaign form by building yup schema. This form has a field called sellers and the field will be array of object with type of {id: number; label: string}. Typescript infers type of sellers object with optional members. This cause type errors in my form.

Here's a minimal example of my Yup schema:

const validationSchema = yup.object().shape({
    sellers: yup
        .array()
        .of(
            yup.object().shape({
                id: yup.number().required().defined(),
                label: yup.string().defined().required(),
            }),
        )
        .required(),
});

Expected TypeScript type of validationSchema:

{
    sellers: {
        id: number;
        label: string;
    }[];
}

Actual TypeScript type of validationSchema inferred:

{
    sellers: {
        id?: number | undefined;
        label?: string | undefined;
    }[];
}

I'm using TypeScript version 5.2.2 and Yup version 1.3.2 I expected TypeScript to recognize the id and label as required due to the .required() and .defined() methods, but it's not happening. Is there a way to force TypeScript to respect the Yup constraints in its type inference?

like image 796
Mehmet Emre Ast Avatar asked Jun 08 '26 05:06

Mehmet Emre Ast


1 Answers

You need to add to tsconfig value: "strict": true

like image 185
andrrrrrre Avatar answered Jun 10 '26 20:06

andrrrrrre