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

Union and Discriminated Union Schema Inference

Inferring discriminated union types from validator schemas that match multiple possible shapes.

Union and Discriminated Union Schema Inference

What you'll learn: How to automatically infer TypeScript types from validator schemas that can match multiple possible object shapes.

When building type-safe APIs, you often need to handle responses or inputs that can be one of several different shapes. Rather than manually writing both the runtime validator schema and the TypeScript type, you can define a single schema that describes multiple possible shapes and let TypeScript infer the union type automatically.

The Union Schema Pattern

With validators like Zod, you can define schemas that accept multiple alternatives using .union() or .or(). TypeScript extracts each possible shape and creates a proper union type:

import { z } from 'zod';

const SuccessSchema = z.object({
  status: z.literal('success'),
  data: z.string()
});

const ErrorSchema = z.object({
  status: z.literal('error'),
  message: z.string()
});

const ResponseSchema = z.union([SuccessSchema, ErrorSchema]);

// TypeScript infers:
// type Response = 
//   | { status: 'success'; data: string }
//   | { status: 'error'; message: string }
type Response = z.infer<typeof ResponseSchema>;

Discriminated Union Inference

When your union schemas include a discriminant property (a literal type that differs across variants), TypeScript recognizes this pattern and enables exhaustive narrowing:

const UserEventSchema = z.discriminatedUnion('type', [
  z.object({ type: z.literal('login'), userId: z.string() }),
  z.object({ type: z.literal('logout'), userId: z.string() }),
  z.object({ type: z.literal('signup'), email: z.string() })
]);

type UserEvent = z.infer<typeof UserEventSchema>;

function handleEvent(event: UserEvent) {
  if (event.type === 'signup') {
    // TypeScript knows: event.email exists
    console.log(event.email);
  }
}

The schema validator ensures runtime correctness while TypeScript's inference gives you compile-time safety and autocomplete—all from one schema definition.

Key Takeaway: Union and discriminated union schema inference lets you define multiple valid shapes in a single validator schema and automatically derive the corresponding TypeScript union type, eliminating duplication and keeping runtime validation aligned with compile-time types.