Course contentsShow
← TypeScript
Lesson 686 of 1,79616. Utility TypesFree lesson

Practical Patterns: Forms and Validation

Apply Pick, Omit, and Record together to type form states, errors, and validation rules.

Practical Patterns: Forms and Validation

What you'll learn: How to combine Pick, Omit, and Record to create type-safe forms with validation rules and error tracking.

The Problem

Forms need three related but distinct type structures: the full data model, the form's editable fields (which might be a subset or have different types), and validation error messages mapped to field names.

The Solution: Combining Utilities

Use Pick to select form fields from a larger model, Omit to exclude non-editable fields, and Record to map field names to validation errors:

type User = {
  id: string;
  email: string;
  username: string;
  password: string;
  createdAt: Date;
};

// Form only edits some fields
type UserFormData = Pick<User, 'email' | 'username' | 'password'>;

// Validation errors for each form field
type FormErrors = Partial<Record<keyof UserFormData, string>>;

// Form state combining data and errors
type FormState = {
  data: UserFormData;
  errors: FormErrors;
};

// Validation rules: each field maps to a validator function
type ValidationRules<T> = Record<keyof T, (value: T[keyof T]) => string | undefined>;

This pattern ensures your form fields, error messages, and validation functions all stay synchronized with your data model. Change UserFormData, and TypeScript automatically updates what's valid in FormErrors and ValidationRules.

Key Takeaway: Combining Pick, Omit, and Record creates a type-safe ecosystem where form data, validation rules, and error messages automatically stay aligned with your model, catching mismatches at compile time.