Course contentsShow
← TypeScript
Lesson 851 of 1,79619. Template Literal TypesFree lesson

Real-World Pattern: Form Field Types

Build comprehensive form field types with errors, values, and handlers from a schema using mapped and template types.

Real-World Pattern: Form Field Types

What you'll learn: How to automatically generate comprehensive form field types—including values, errors, and handlers—from a schema definition using mapped and template literal types.

The Pattern

Forms are everywhere in web applications, and they require a surprising amount of type infrastructure. For each field, you typically need:

  • The current value type
  • Potential error messages
  • Change handlers
  • Validation state

Template literal types let you generate all of these automatically from a single schema.

Building the Pattern

Think of this like a factory that takes a simple blueprint and produces all the machinery needed to run a form. You define your fields once, and TypeScript manufactures all the associated types.

Start with a schema that maps field names to their value types:

type FormSchema = {
  email: string;
  age: number;
  subscribe: boolean;
};

Now generate field value types, error types, and handler types:

type FormValues<T> = T;

type FormErrors<T> = {
  [K in keyof T]?: string;
};

type FormHandlers<T> = {
  [K in keyof T as `on${Capitalize<string & K>}Change`]: (value: T[K]) => void;
};

Combine them into a complete form type:

type FormState<T> = {
  values: FormValues<T>;
  errors: FormErrors<T>;
  handlers: FormHandlers<T>;
};

type MyForm = FormState<FormSchema>;
// Result:
// {
//   values: { email: string; age: number; subscribe: boolean };
//   errors: { email?: string; age?: string; subscribe?: string };
//   handlers: {
//     onEmailChange: (value: string) => void;
//     onAgeChange: (value: number) => void;
//     onSubscribeChange: (value: boolean) => void;
//   };
// }

This pattern scales beautifully—add a field to your schema, and all related types update automatically.

Key Takeaway: Template literal types with mapped types transform a simple field schema into a complete, type-safe form API—generating values, errors, and handlers without manual repetition.