Skip to content

Typed Form Handler

Medium ~25 min

What you'll build

A FormHandler class that takes a field definition object, produces typed getters/setters for each field, and runs validators with typed error messages.

Goals

  • Use mapped types to derive form value types
  • Type form field definitions and validators
  • Build a reactive form state system
  • Apply keyof and indexed access types practically

Prerequisites

  • Mapped types
  • Utility types
  • Generics

Steps

  1. 1

    Define the field and form types

    Create a FieldDef interface for individual fields and a mapped type that derives the values type from a field definition record.

    Code
    interface FieldDef<T> {
      initial: T;
      validate?: (value: T) => string | null;
    }
    type FormValues<F> = { [K in keyof F]: F[K] extends FieldDef<infer T> ? T : never };

    Expected result

    Field definition and form values types are defined using conditional type inference.

  2. 2

    Write the form handler class

    Create a generic FormHandler that stores values, runs validators, and provides typed access to each field.

    Code
    class FormHandler<F extends Record<string, FieldDef<any>>> {
      private values: FormValues<F>;
      private errors: Partial<Record<keyof F, string>> = {};
      constructor(private defs: F) {
        this.values = Object.fromEntries(
          Object.entries(defs).map(([k, d]) => [k, d.initial])
        ) as FormValues<F>;
      }
      get<K extends keyof F>(key: K): FormValues<F>[K] { return this.values[key]; }
      set<K extends keyof F>(key: K, value: FormValues<F>[K]): void {
        this.values[key] = value;
        const validate = this.defs[key].validate;
        this.errors[key] = validate ? validate(value) : undefined;
      }
      hasErrors(): boolean { return Object.values(this.errors).some(Boolean); }
    }

    Expected result

    A form handler with typed get/set methods and automatic validation.

  3. 3

    Use the form handler

    Define form fields with validators and use the handler. Each field access is type-safe.

    Code
    const form = new FormHandler({
      name: { initial: "", validate: v => v.length < 2 ? "Too short" : null },
      age: { initial: 0, validate: v => v < 0 ? "Negative" : null },
    });
    form.set("name", "Alice"); // type-safe: must be string
    form.set("age", 30); // type-safe: must be number
    console.log(form.get("name")); // "Alice"
    console.log(form.hasErrors()); // false

    Expected result

    A fully typed form with validation. Wrong value types are compile errors.

  4. 4

    Add type guards & runtime checks

    Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.

    Code
    type User = { id: number; name: string };
    
    function isUser(value: unknown): value is User {
      if (typeof value !== "object" || value === null) return false;
      const obj = value as Record<string, unknown>;
      return typeof obj.id === "number" && typeof obj.name === "string";
    }
    
    // Usage with unknown input
    const data: unknown = JSON.parse(rawJson);
    if (isUser(data)) {
      console.log(data.name); // TS knows data is User here
    } else {
      console.error("Invalid user data");
    }

    Expected result

    When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.

  5. 5

    Add generic utility functions

    Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.

    Code
    function groupBy<T, K extends string | number>(
      items: T[],
      keyFn: (item: T) => K
    ): Record<K, T[]> {
      const result = {} as Record<K, T[]>;
      for (const item of items) {
        const key = keyFn(item);
        (result[key] ??= []).push(item);
      }
      return result;
    }
    
    // Usage
    const byAge = groupBy(users, u => u.age);

    Expected result

    groupBy groups any array by key, returning a type-safe Record.

Try it yourself

What you learned

You built a type-safe form system using mapped types and conditional type inference. The form values type is derived from the field definitions — adding a field automatically updates all related types. This pattern powers libraries like React Hook Form and Formik.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic