Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 5 · Lesson 44 · 6 min read

TypeScript Utility Types and Mapped Types

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: One Source of Truth for an Entity, a Form and Settings
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Derive types from other types instead of duplicating them, using the built-in utility types, mapped types with key remapping, conditional types with infer, template literal types and the typeof and as const operators, so that a single source of truth keeps related types in sync.

Concept Explanation

Duplicated types drift. If a User type exists in one file and a hand-written UserUpdate type in another, the day someone adds a field to User, UserUpdate is silently wrong. TypeScript's type-level tools let you derive one type from another, so the relationship is explicit and changes propagate automatically. The goal is not cleverness; it is a single source of truth.

The built-in utility types cover most needs. Partial<T> makes every property optional, which suits patch payloads. Required<T> does the opposite. Readonly<T> prevents assignment. Pick<T, K> keeps some properties and Omit<T, K> removes them, so a create payload can be Omit<User, 'id' | 'createdAt'>. Record<K, V> builds an object type with keys K. For functions, ReturnType, Parameters and Awaited extract their pieces, which is useful for typing values returned by functions you do not control. NonNullable removes null and undefined, and Extract and Exclude filter union members.

Mapped types are how those utilities are built, and you can write your own. The syntax { [K in keyof T]: ... } produces a new type with one property per key of T, with modifiers to add or remove readonly and optional. Key remapping with as lets you rename keys, for example producing setter names from field names, or filter keys out by mapping them to never. Conditional types, written T extends U ? X : Y, choose a type based on another, and infer captures part of a type inside a condition, which is how ReturnType extracts a function's return type.

Template literal types bring string manipulation to the type level. A template literal type that prefixes on to the capitalized event name turns the union 'click' | 'focus' into 'onClick' | 'onFocus'. Combined with mapped types they can generate event handler names, CSS custom property names or route parameter types from a route string. Design systems use them to type spacing tokens and responsive props.

Values can be the source of truth as well. typeof applied to a value gives its type, and as const makes TypeScript infer the narrowest literal types and readonly arrays. So a const array of roles, as const, can produce the union type of its elements with typeof roles[number], and the same array can be used at run time for validation or rendering options. The satisfies operator checks that a value conforms to a type while keeping its own precise inferred type, ideal for configuration objects. Type-level code should stay readable: if a type needs a comment to explain it, consider whether a simpler explicit type would serve the team better.

ToolExampleProduces
Partial and OmitPartial<Omit<User, 'id'>>Optional fields without id
PickPick<User, 'id' or 'name'>Only those properties
RecordRecord<Locale, string>Object keyed by every locale
ReturnType and AwaitedAwaited<ReturnType<typeof fetchUser>>The resolved result type
Mapped type with asK in keyof T, renamed to set plus Capitalize of KRenamed keys
Conditional with inferT extends Promise<infer U> ? U : TUnwrapped type
as const with typeoftypeof ROLES[number]Union of literal values
satisfiesconfig satisfies ConfigChecked but still precise

Worked Example: One Source of Truth for an Entity, a Form and Settings

All related types are derived from the User type and from constant arrays, so adding a field or a role updates everything automatically.

Shell
// Values as the source of truth
export const ROLES = ['viewer', 'editor', 'admin'] as const;
export type Role = typeof ROLES[number];                 // 'viewer' | 'editor' | 'admin'

export interface User {
  id: string;
  email: string;
  name: string;
  role: Role;
  createdAt: string;
}

// Derived payload types
export type CreateUser = Omit<User, 'id' | 'createdAt'>;
export type UpdateUser = Partial<Omit<User, 'id' | 'createdAt'>> & Pick<User, 'id'>;
export type UserSummary = Pick<User, 'id' | 'name'>;

// Form state: every field becomes a string plus an optional error, derived by a mapped type
export type FormState<T> = {
  [K in keyof T]: { value: string; error?: string; touched: boolean };
};
type CreateUserForm = FormState<CreateUser>;             // email, name, role

// Setter names from field names with key remapping and template literals
type Setters<T> = { [K in keyof T & string as `set${Capitalize<K>}`]: (value: T[K]) => void };
type UserSetters = Setters<CreateUser>;                  // setEmail, setName, setRole

// Unwrap the type a function resolves to
async function fetchUser(id: string) { return { ...(await getJSON<User>(`/api/users/${id}`)), loadedAt: Date.now() }; }
type LoadedUser = Awaited<ReturnType<typeof fetchUser>>; // User & { loadedAt: number }

// satisfies: checked against the type, but keys stay precise
type Locale = 'en' | 'fr' | 'ar';
const messages = {
  en: { greeting: 'Hello' },
  fr: { greeting: 'Bonjour' },
  ar: { greeting: 'مرحبا' },
} satisfies Record<Locale, { greeting: string }>;
// Removing 'ar' above is a compile error: every locale must be present

Adding 'owner' to ROLES updates Role, User, CreateUser, the form state and every switch over roles that has an exhaustive check, with no other edits.

A constant ROLES array produces the Role union. The User interface uses it, and the create payload, update payload, summary and form state are all derived from User with Omit, Partial, Pick and a mapped type, so one change updates every type.
A constant ROLES array produces the Role union. The User interface uses it, and the create payload, update payload, summary and form state are all derived from User with Omit, Partial, Pick and a mapped type, so one change updates every type.

Real-World Examples

  • The satisfies operator was added in TypeScript 4.9 in 2022 to address a long-requested need: validating that configuration objects match a type without widening their inferred types, which libraries such as Vite and Tailwind now show in their typed configuration examples.
  • Routers such as TanStack Router and the typed routes feature in Next.js use template literal and mapped types to derive the parameters of each route from its path string, so navigating to a route without its required parameters is a compile error.
Key TakeawaysDerive TypeScript types from each other instead of duplicating them, so one change to a type flows everywhere it is used. Use Omit, Pick, Partial and Record for payloads, ReturnType and Awaited for functions you do not own, mapped types with as for transformations, conditional types with infer for extraction and template literal types for generated names. Use as const and typeof to turn values into types, satisfies to check without widening, and keep type-level code readable.

Review Questions & Answers

A separately written type can drift when User changes, so a new required field would be missing from the create payload without any error. Omit<User, 'id' | 'createdAt'> always reflects the current User, making the relationship explicit and automatic.

It makes TypeScript infer the narrowest types: string literals instead of string, and readonly tuples instead of arrays. That lets typeof ROLES[number] produce the exact union of the array's values.

An annotation makes the value's type exactly the annotated type, widening it and losing precise information such as specific keys. satisfies checks that the value conforms to the type but keeps the value's own inferred, more precise type.

In a mapped type, as followed by a template literal type renames each key, for example turning email into setEmail with Capitalize. Mapping a key to never removes it, so the same mechanism can also filter properties.