Lab 04: Runtime Safety

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

Runtime type safety architecture: Zod as single source of truth (infer TypeScript types + runtime validators), comparison with ArkType/io-ts, generating OpenAPI schemas from Zod, and type-safe environment variables with t3-env.


Step 1: The Problem with TypeScript Types Alone

// TypeScript types are ERASED at runtime
// This is perfectly valid TypeScript but unsafe at runtime:

interface User {
  id: string;
  email: string;
  role: 'admin' | 'user';
}

async function getUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  const data = await response.json();
  return data as User;  // DANGEROUS: no runtime validation
  // If API returns { id: 1, emal: "typo" }, TypeScript is blind to this
}

Step 2: Zod — Single Source of Truth


Step 3: Advanced Zod Patterns


Step 4: Zod → OpenAPI Schema Generation


Step 5: Library Comparison


Step 6: Type-Safe Environment Variables


Step 7: Middleware Validation Pattern


Step 8: Capstone — Zod Runtime Validation

📸 Verified Output:


Summary

Library
Bundle
DX
Ecosystem
Best For

Zod

~14KB

Excellent

Huge

General purpose

ArkType

~10KB

Concise

Growing

Performance

Valibot

~8KB

Good

Good

Bundle-sensitive

io-ts

~5KB

Verbose

Mature

fp-ts integration

t3-env

~3KB

Excellent

Niche

Env variables

Last updated