Generics and Advanced Types

Write reusable, precise types with generics, utility types, keyof, mapped and conditional types.

Advanced · about 8 hours · difficulty 4/5

Learn first: TypeScript Fundamentals

Once basic annotations feel natural, you will hit code that works for many types: a useFetch hook, a table component, a typed event emitter. Generics and type operators let you describe these precisely instead of falling back to any.

Generics

A generic is a type parameter: function first<T>(items: T[]): T | undefined. The caller's argument decides T. Add constraints with extends (<T extends { id: string }>) and defaults when useful. React components and hooks are generic all the time: useState<User | null>(null).

Utility types you will use weekly

  • Partial<T>, Required<T>, Readonly<T>
  • Pick<T, K> and Omit<T, K> to derive form or API shapes from a model
  • Record<K, V>, ReturnType<F>, Parameters<F>, Awaited<T>, NonNullable<T>

Type operators

  • keyof T gives the union of keys; indexed access T["name"] gets a property type.
  • typeof value lifts a runtime value into a type, great with as const objects.
  • Mapped types transform every key: { [K in keyof T]: T[K] | null }.
  • Conditional types and infer branch on types; mostly library territory.
  • Template literal types build string unions like `on${Capitalize<Event>}`.
  • satisfies checks a value against a type while keeping its narrow inferred type.

Pitfalls

Clever types are a maintenance cost. If a type needs a paragraph of explanation, simplify it. Prefer deriving types from one source of truth (a Zod schema or a model type) over duplicating them.

Good enough to move on

You can write a generic list component or fetch helper, derive form types with Pick and Partial, and read the types in a library's .d.ts file.

Key concepts

  • Generic functions and constraints
  • Built-in utility types
  • keyof, typeof and indexed access
  • as const and satisfies
  • Mapped types
  • Conditional types and infer
  • Template literal types

Mini project

Write a typed fetch helper `request<T>(url, schema)` and a generic `DataTable<T>` whose column definitions only accept keys of T, then derive create/update DTO types from one model with utility types.

Check yourself

What does `Omit<User, "id" | "createdAt">` produce, and why is it better than writing a second interface by hand?

Free resources