Course contentsShow
← TypeScript
Lesson 1301 of 1,79630. Type-Safe APIsFree lesson

Yup Schema Inference with InferType

Using Yup's InferType utility to extract TypeScript types from Yup validation schemas.

Yup Schema Inference with InferType

What you'll learn: How to automatically generate TypeScript types from Yup validation schemas using the InferType utility, eliminating duplication between runtime validation and type definitions.

The Problem InferType Solves

In the previous lesson, you saw Zod's schema-first approach where types are inferred from schemas. Yup offers a similar capability through its InferType utility. Instead of writing a Yup schema for runtime validation and a separate TypeScript interface, you can define the schema once and extract the TypeScript type automatically.

Plain English Explanation

Think of InferType as a translator that reads your Yup schema (which is runtime validation) and converts it into a TypeScript type (which is compile-time checking). You write the validation rules once, and TypeScript automatically understands what shape your data should have.

Basic InferType Usage

When you create a Yup schema, you can use InferType to extract the corresponding TypeScript type:

import * as yup from 'yup';
import { InferType } from 'yup';

const userSchema = yup.object({
  name: yup.string().required(),
  age: yup.number().required(),
  email: yup.string().email().optional()
});

// Extract the TypeScript type from the schema
type User = InferType<typeof userSchema>;

// User is now equivalent to:
// {
//   name: string;
//   age: number;
//   email?: string | undefined;
// }

Notice how required() fields become non-optional in the type, while optional() fields become optional properties with ?.

How InferType Interprets Schema Rules

InferType reads your Yup schema and translates validation rules into type information:

  • yup.string() becomes string
  • yup.number() becomes number
  • yup.boolean() becomes boolean
  • .required() makes the property non-optional
  • .optional() adds ? to the property and includes undefined in the type
  • .nullable() adds | null to the type

This creates a single source of truth: your schema defines both validation behavior and the TypeScript type.

Key Takeaway: Yup's InferType<typeof schema> utility automatically generates TypeScript types from validation schemas, ensuring your runtime validation and compile-time types stay perfectly synchronized without manual duplication.