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

Composing Inferred Types Across Schemas

Building complex types by combining and extending multiple validator schemas with correct type inference.

Composing Inferred Types Across Schemas

What you'll learn: How to build complex, type-safe structures by combining multiple validator schemas while maintaining automatic type inference.


When you've built several schemas with runtime validators like Zod, you often need to create new types by combining, extending, or transforming existing ones. The power of schema inference means you can compose schemas together and TypeScript will automatically derive the combined type—no manual duplication needed.

The Composition Problem

Imagine you have separate schemas for User, Address, and Preferences. Instead of recreating types manually when you need a "UserProfile" that combines all three, you can compose the schemas themselves and let TypeScript infer the complete type.

Basic Schema Extension

You can extend one schema with additional fields:

import { z } from 'zod';

const BaseUserSchema = z.object({
  id: z.string(),
  email: z.string().email()
});

const FullUserSchema = BaseUserSchema.extend({
  name: z.string(),
  age: z.number()
});

type FullUser = z.infer<typeof FullUserSchema>;
// { id: string; email: string; name: string; age: number; }

Merging Independent Schemas

You can merge completely separate schemas:

const AddressSchema = z.object({
  street: z.string(),
  city: z.string()
});

const PreferencesSchema = z.object({
  theme: z.union([z.literal('light'), z.literal('dark')]),
  notifications: z.boolean()
});

const UserProfileSchema = FullUserSchema.merge(AddressSchema).merge(PreferencesSchema);

type UserProfile = z.infer<typeof UserProfileSchema>;
// All fields from FullUser + Address + Preferences combined

Picking and Omitting from Composed Types

You can selectively extract or exclude fields from composed schemas:

const PublicUserSchema = UserProfileSchema.pick({
  id: true,
  name: true,
  theme: true
});

type PublicUser = z.infer<typeof PublicUserSchema>;
// Only: { id: string; name: string; theme: 'light' | 'dark'; }

The beauty here is that validation and types stay synchronized—change your base schema, and all composed schemas automatically reflect that change at both runtime and compile time.

Key Takeaway: Schema composition with .extend(), .merge(), .pick(), and .omit() lets you build complex types by combining simpler schemas, with TypeScript inferring the complete shape automatically—keeping your validation logic and types in perfect sync.