DEV Community

Dusan Petkovic
Dusan Petkovic

Posted on

Latest version of Yup and Typescript issues that annoy me!

Hey everyone, I've recently started a project where I am using Yup with Vite and the latest version of React, but I'm facing some issues.


Namely, I've used Yup to generate validation schemas for data received from an endpoint, such as a POST request body. Then, I realized I could infer my entire Entities from the Yup schemas.

So, I wrote code like the following:

export const questionEntitySchema = Yup.object().shape({
  questionText: Yup.string().required(),
  id: Yup.string().required(),
}).required();

export const getQuestionsSchema = Yup.object().shape({
  questions: Yup.array().of(questionEntitySchema).required(),
});

Enter fullscreen mode Exit fullscreen mode

And I expected the type of getQuestionsSchema to be like the following:

// to infer the type with Yup utility
export type TGetQuestions = Yup.InferType<typeof getQuestionsSchema>;

// what I expect as the inferred type for TGetQuestions
type TGetQuestions = {
    questions: {
        questionText: string;
        id: string;
    }[];
}
Enter fullscreen mode Exit fullscreen mode

However, the problem is that I don't get what I expected; everything I get becomes OPTIONAL, which contradicts the required statements in the schema definition.

// example of what is actually inferred 

type TGetQuestions = {
    questions?: {
        questionText?: string;
        id?: string;
    }[];
}
Enter fullscreen mode Exit fullscreen mode

If it worked as described in the official docs, it would be very convenient to declaratively describe the Entities and DTOs with Yup schemas and then accurately infer them. But from my testing, it doesn't seem to work. I'm not sure if it's a TypeScript-specific issue.

it would be nice to have some additional eyes on this. Maybe I'm doing something wrong here.

Thanks!

Top comments (0)