TypeScript Reference ยท Concepts and Comparisons
Type-level programming in TypeScript
Compute with types in TypeScript using conditional, mapped, template literal and recursive types, plus practical limits and testing tips.
TypeScript's type system is a small functional language. Types are the values, generics are functions, conditional types are if, mapped types are loops over keys, and recursion lets you traverse structures. Everything is evaluated by the compiler, and nothing remains at run time.
Type-level programming is how utility types such as Partial, Pick and ReturnType are built, and how libraries give precise types to routers, query builders and form libraries. Used in moderation it removes duplication; used heavily it slows the editor and confuses readers.
type ElementOf<T> = T extends (infer U)[] ? U : never; type N = ElementOf<number[]>; // number
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
The toolbox
- Conditional types (
T extends U ? X : Y) branch on assignability and distribute over unions whenTis a bare type parameter. infercaptures a part of a matched type, such as an element, a return type or a string fragment.- Mapped types transform every key;
asclauses rename or drop keys; modifiers add or removereadonlyand?. - Template literal types build and parse string types.
- Indexed access and
keyofread and list members. - Recursion handles lists, nested objects and strings. Tail-recursive conditional types are optimized to a limit of about a thousand steps, other recursion stops earlier.
Usage notes
- Test types like code. Assert expected results with helper types or
@ts-expect-error; see Testing types. - Keep results readable. Intermediate aliases with names make error messages and hover text understandable.
- Watch performance. Deep unions and recursion can trigger "Type instantiation is excessively deep" (TS2589) or slow checking; see Compiler performance.
- Do not simulate a runtime. Arithmetic and parsers in types are fun, but rarely worth the maintenance cost.
- Prefer built-in utilities over hand-rolled ones.
- Hide complexity behind a simple exported signature so callers never see the machinery.