Skip to content
LumenaryAcademy
Professional 65 min

Utility, mapped and conditional types

Computing types from other types, so that one definition drives the rest, and knowing when to stop.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

One source of truth

A User type appears in a sign-up form (without an id, which the server assigns), in a profile editor (every field optional), in a list (just id and name), and in the database layer (everything, read-only). Writing four separate interfaces works for a week. Then someone adds phone to one of them and not the others, and the types quietly disagree with each other and with reality.

TypeScript's answer is to compute types from types. Write User once, and derive the rest: Omit<User, "id">, Partial<User>, Pick<User, "id" | "name">, Readonly<User>. Change User, and everything derived from it changes too. The machinery behind these utilities, mapped types and conditional types, is available to you as well, and it turns the type system into a small programming language of its own: functions from types to types. This lesson covers the built-in utilities first, then the machinery, then the judgement about how far to take it.

Worked examplesH

The built-in utility types

typescript
// Utility types: new types computed from existing ones, so they never drift apart.
interface User {
  id: string;
  name: string;
  email: string;
  city?: string;
  joined: Date;
}

type UserPatch = Partial<Omit<User, "id" | "joined">>;     // every editable field, all optional
type UserPreview = Pick<User, "id" | "name">;               // just what a list needs
type NewUser = Omit<User, "id" | "joined">;                 // what a sign-up form collects

const users = new Map<string, Readonly<User>>();

function createUser(input: NewUser): Readonly<User> {
  const user: User = { ...input, id: `u-${users.size + 1}`, joined: new Date(Date.UTC(2026, 10, 19)) };
  users.set(user.id, user);
  return user;
}

function updateUser(id: string, patch: UserPatch): Readonly<User> {
  const current = users.get(id);
  if (current === undefined) throw new Error(`no user ${id}`);
  const updated = { ...current, ...patch };
  users.set(id, updated);
  return updated;
}

const preview = (u: User): UserPreview => ({ id: u.id, name: u.name });

const ana = createUser({ name: "Ana Folau", email: "ana@example.org" });
const moved = updateUser(ana.id, { city: "Nuku'alofa" });
console.log(moved.city, moved.name, moved.joined.toISOString().slice(0, 10));
console.log(preview(moved));

// Types computed from functions and values.
async function loadSettings() {
  return { theme: "dark" as "dark" | "light", fontSize: 16 };
}
type Settings = Awaited<ReturnType<typeof loadSettings>>;   // { theme: "dark" | "light"; fontSize: number }
type CreateArgs = Parameters<typeof createUser>;            // [input: NewUser]

const s: Settings = { theme: "light", fontSize: 14 };
const args: CreateArgs = [{ name: "Bo", email: "bo@example.org" }];
console.log(s.theme, args[0].name, users.size);

// Union utilities.
type Status = "draft" | "review" | "published" | "archived";
type Visible = Exclude<Status, "draft" | "archived">;       // "review" | "published"
const visible: Visible[] = ["review", "published"];
console.log(visible.join(", "));

export {};
text
Nuku'alofa Ana Folau 2026-11-19
{ id: 'u-1', name: 'Ana Folau' }
light Bo 1
review, published

The utilities you will use every week:

UtilityProducesTypical use
Partial<T>every property optionalpatches, updates, defaults to merge
Required<T>every property requiredthe result of filling in defaults
Readonly<T>every property readonlydata that must not be mutated
Pick<T, K>only the properties Ka view of part of an object
Omit<T, K>all but the properties Kinput without server-assigned fields
Record<K, V>an object with keys K, values Vlookup tables, dictionaries
Exclude<U, X>, Extract<U, X>union members not assignable / assignable to Xfiltering literal unions
NonNullable<T>T without null and undefinedafter a check
ReturnType<F>, Parameters<F>a function type's result / parameter tuplewrapping functions you don't own
Awaited<T>what await would produceresults of async functions
InstanceType<C>, ConstructorParameters<C>from a class's constructor typefactories

The program uses them as a real code base would. UserPatch is "any editable field, all optional", so updateUser(ana.id, { id: "u-99" }) is rejected ('id' does not exist in type 'Partial<Omit<User, "id" | "joined">>'), and the Readonly<User> returned from the store means moved.name = "Ana F." fails with Cannot assign to 'name' because it is a read-only property. Settings is computed from what loadSettings returns: typeof loadSettings turns the value into its function type, ReturnType extracts Promise<...>, and Awaited unwraps the promise. If someone adds a field to the settings, Settings gains it automatically.

A word on the two meanings of typeof. In an expression, typeof x is JavaScript's run-time operator and produces a string such as "object". In a type position, typeof x is TypeScript's type query and produces the static type of the variable x. The compiler always knows which one you mean from where it appears, and the type query is the bridge from the world of values to the world of types: typeof someConstant, keyof typeof someObject, ReturnType<typeof someFunction>. Most derived types in real code begin with it.

DefinitionsH

Mapped types and template literal types

Definition— mapped type

A mapped type, { [K in Keys]: Type }, builds an object type with one property for each member K of a union of keys, where Type may refer to K. Iterating over keyof T transforms each property of T. Modifiers add or remove readonly and ? (+readonly, -readonly, +?, -?), and an as clause renames keys or, by mapping them to never, removes them.

Partial<T> itself is defined in TypeScript's standard library as { [P in keyof T]?: T[P] }: a mapped type adding ?. Here are some of your own:

typescript
// Mapped types: build an object type by transforming each property of another.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };      // remove readonly
type Nullable<T> = { [K in keyof T]: T[K] | null };        // allow null everywhere
type Getters<T> = {
  [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];  // rename keys with `as`
};

interface Station {
  readonly code: string;
  name: string;
  elevation: number;
}

// A function whose return type is computed by Getters<T>.
function makeGetters<T extends object>(obj: T): Getters<T> {
  const result: Record<string, () => unknown> = {};
  for (const key of Object.keys(obj) as (keyof T & string)[]) {
    result[`get${key[0].toUpperCase()}${key.slice(1)}`] = () => obj[key];
  }
  return result as Getters<T>;
}

const lhasa: Station = { code: "LXA", name: "Lhasa", elevation: 3650 };
const g = makeGetters(lhasa);          // { getCode: () => string; getName: ...; getElevation: () => number }
console.log(g.getName(), g.getElevation() + 10, Object.keys(g));

const draft: Mutable<Station> = { ...lhasa };
draft.code = "LHA";                    // allowed: readonly was removed
const blank: Nullable<Station> = { code: "TBD", name: null, elevation: null };
console.log(draft.code, blank.name ?? "(unnamed)");

// Filtering keys: keep only the properties whose values are numbers.
type NumericKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];
function total<T>(rows: T[], key: NumericKeys<T>): number {
  return rows.reduce((sum, row) => sum + (row[key] as number), 0);
}
const stations: Station[] = [lhasa, { code: "LPB", name: "La Paz", elevation: 3640 }];
console.log(total(stations, "elevation"));

export {};
text
Lhasa 3660 [ 'getCode', 'getName', 'getElevation' ]
LHA (unnamed)
7290
  • Mutable<T> removes readonly with -readonly; Nullable<T> changes every property's type. These are one-line transformations of every property at once.
  • Getters<T> renames keys with as and a template literal type: for each string key K, the new key is `get${Capitalize<K>}`, so name becomes getName. Capitalize, Uncapitalize, Uppercase and Lowercase are built-in string transformations at the type level. The return type of makeGetters is thereby computed from its argument, and the editor offers getCode, getName and getElevation on g. Notice that the implementation needs an assertion (as Getters<T>): the type system cannot follow string manipulation done at run time. This is typical, and a good reason to keep such functions small and tested.
  • NumericKeys<T> is a classic idiom. The mapped type replaces each property's type with its own key if the value is a number and with never otherwise; indexing the result with [keyof T] collects the surviving keys into a union. For Station, that is just "elevation", so total(stations, "name") is rejected with Argument of type '"name"' is not assignable to parameter of type '"elevation"'. This is the technique the generics lesson promised for constraining a key to properties of a certain type.

Template literal types are useful on their own, too: type EventName = `on${Capitalize<"click" | "focus">}` is "onClick" | "onFocus", and `#${string}` (lesson two) describes any string starting with #.

IntuitionH

Conditional types and infer

Definition— conditional type

A conditional type, T extends U ? X : Y, evaluates to X if T is assignable to U, and to Y otherwise. In the extends clause, infer Name introduces a type variable that TypeScript fills in by matching, which lets you extract part of a type. When T is a bare type parameter and receives a union, the conditional is applied to each member separately and the results are joined: it distributes.

typescript
// Conditional types choose a type by testing another; `infer` captures part of a type.
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type IsString<T> = T extends string ? "yes" : "no";

type A = ElementOf<string[]>;                 // string
type B = IsString<"hello" | 42>;              // "yes" | "no": conditional types distribute over unions

const a: A = "an element";
const b: B[] = ["yes", "no"];
console.log(a, b);

// Template literal types + infer: extract route parameters from a path pattern.
type RouteParams<Path extends string> =
  Path extends `${string}:${infer Param}/${infer Rest}`
    ? { [K in Param | keyof RouteParams<`/${Rest}`>]: string }
    : Path extends `${string}:${infer Param}`
      ? { [K in Param]: string }
      : {};

function buildPath<const P extends string>(pattern: P, params: RouteParams<P>): string {
  return pattern.replace(/:(\w+)/g, (_, name: string) =>
    encodeURIComponent((params as Record<string, string>)[name]),
  );
}

console.log(buildPath("/users/:userId/posts/:postId", { userId: "42", postId: "hello world" }));
console.log(buildPath("/cities/:name", { name: "São Paulo" }));
console.log(buildPath("/about", {}));

// A tiny type-level test kit: these lines compile only if the types are what we claim.
type Equal<X, Y> = [X] extends [Y] ? ([Y] extends [X] ? true : false) : false;
type Expect<T extends true> = T;
type Tests = [
  Expect<Equal<ElementOf<number[]>, number>>,
  Expect<Equal<RouteParams<"/a/:x/b/:y">, { x: string; y: string }>>,
  Expect<Equal<Awaited<Promise<Promise<boolean>>>, boolean>>,
];
const passed: Tests["length"] = 3;
console.log(`${passed} type-level tests compiled`);

export {};
text
an element [ 'yes', 'no' ]
/users/42/posts/hello%20world
/cities/S%C3%A3o%20Paulo
/about
3 type-level tests compiled
  • ElementOf<T> asks "is T an array of something?" and, if so, infer E captures that something. ElementOf<string[]> is string; ElementOf<string> is never. The built-ins ReturnType, Parameters and Awaited are written exactly this way.
  • Distribution. IsString<"hello" | 42> is evaluated for "hello" and for 42 separately, giving "yes" | "no". It is usually what you want (it is how Exclude works); when it isn't, wrap both sides in brackets, [T] extends [U], to compare the union as a whole, as Equal does.
  • RouteParams combines everything: template literal types with infer pull each :param out of a path pattern, recursion handles any number of them, and a mapped type turns them into an object type. buildPath then demands exactly the right parameters for each pattern: buildPath("/users/:userId", { id: "42" }) fails with 'id' does not exist in type '{ userId: string; }'. Web frameworks and routers use this technique to type route handlers from their URL patterns.
  • Testing types. Equal and Expect form a minimal test kit: each Expect<Equal<A, B>> compiles only if A and B are the same type. Add a false claim, such as Expect<Equal<ElementOf<number[]>, string>>, and the build fails with Type 'false' does not satisfy the constraint 'true'. Libraries with complex types keep suites of such tests, often with a more careful Equal (this simple one cannot tell any apart from other types) or a dedicated tool.

Conditional types and recursion make TypeScript's type system expressive enough to compute almost anything, which is both fascinating and a warning. Lumenary Math's lambda calculus shows how little a language needs in order to compute everything.

ComputationC

Worked example: types derived from one value

The most useful everyday application of this lesson is not a clever recursive type but the habit of deriving types from a single run-time value. Here a table of roles and their permissions is the only place either is written down:

typescript
// One `as const` value drives every type: roles, permissions and a checked lookup.
const PERMISSIONS = {
  viewer: ["read"],
  editor: ["read", "write"],
  admin: ["read", "write", "delete", "invite"],
} as const satisfies Record<string, readonly string[]>;

type Role = keyof typeof PERMISSIONS;                          // "viewer" | "editor" | "admin"
type Permission = (typeof PERMISSIONS)[Role][number];          // "read" | "write" | "delete" | "invite"
type PermissionsOf<R extends Role> = (typeof PERMISSIONS)[R][number];

function can(role: Role, permission: Permission): boolean {
  return (PERMISSIONS[role] as readonly Permission[]).includes(permission);
}

// Exclude and the derived types work together.
type AdminOnly = Exclude<Permission, PermissionsOf<"editor">>;  // "delete" | "invite"
const adminOnly: AdminOnly[] = ["delete", "invite"];

const roles = Object.keys(PERMISSIONS) as Role[];
for (const role of roles) {
  const allowed = adminOnly.filter((p) => can(role, p));
  console.log(`${role.padEnd(7)} write=${can(role, "write")} admin-only=${allowed.join("+") || "none"}`);
}

export {};
text
viewer  write=false admin-only=none
editor  write=true admin-only=none
admin   write=true admin-only=delete+invite

as const keeps every string as a literal, and satisfies checks the overall shape without widening it (lesson two). From there, each type is one step: keyof typeof PERMISSIONS is the union of role names; indexing with [Role][number] collects every permission that appears in any role; PermissionsOf<R> does the same for one role; and Exclude subtracts the editor's permissions to find what only an admin can do. Nothing is written twice. Add a "moderator" role with a "hide" permission to the object, and Role, Permission, can and every caller update themselves, while a call with a role or permission that doesn't exist is rejected. With a two-role version of the table, for example:

text
main.ts(8,5): error TS2345: Argument of type '"owner"' is not assignable to parameter of type '"viewer" | "editor"'.
main.ts(9,15): error TS2345: Argument of type '"publish"' is not assignable to parameter of type '"read" | "write"'.

The two assertions that remain (as readonly Permission[] and as Role[]) are the familiar places where run-time APIs, includes and Object.keys, are typed more loosely than our data; each is local and obviously correct. This pattern, a constant table as the source of truth with types computed from it, is how many teams type feature flags, translation keys, analytics events, API endpoints and design tokens.

ExplanationH

How far to go

Type-level programming is seductive. Every experienced TypeScript developer has written a type so clever that, six months later, nobody (including its author) could change it. Some guidance from practice:

  • Use the built-ins first. Partial, Pick, Omit, ReturnType and friends cover most needs and are understood by every reader.
  • Derive types from values where possible. A const object or array with as const and satisfies, plus typeof and keyof, often replaces a page of hand-written types with one source of truth that is also usable at run time.
  • Put complex types at library boundaries, not in application code. A router, a form library or a query builder may justify a RouteParams-style type, written once, tested with type-level tests, and used by hundreds of call sites that never see its insides. Application code should read like ordinary code.
  • Name the pieces. A conditional type split into small, named aliases (ElementOf, NumericKeys) is far easier to follow than one nested expression.
  • Watch the compiler's speed. Deeply recursive types can slow down type checking and the editor noticeably; TypeScript limits recursion depth and reports Type instantiation is excessively deep and possibly infinite when you hit the limit. The --extendedDiagnostics flag shows where checking time goes.
  • Error messages are part of the design. A type that produces a 40-line error for a simple mistake is a bad type, however correct.
Common misconceptionsH

Common misconceptions

Misconception

"Partial<T> makes nested objects partial too." It is shallow: only the top-level properties become optional. A DeepPartial must be written recursively, and is a good exercise.

Misconception

"Omit<T, K> checks that K is a key of T." It doesn't: Omit<User, "idd"> silently omits nothing. Some teams define a stricter version with K extends keyof T.

Misconception

"keyof and Object.keys give the same thing." keyof T is the set of keys the type declares. Object.keys(obj) returns the keys the object actually has at run time, which may include extra ones (structural typing allows them), so TypeScript types its result as string[], not (keyof T)[]. That is why the lesson's examples assert as Role[] only where the object is a known constant.

Misconception

"Mapped and conditional types run when the program runs." They exist only in the checker. A function whose type says it returns Getters<T> must still construct those getters at run time, and the compiler usually cannot verify that it does.

Misconception

"Conditional types always treat a union as one type." A conditional on a bare type parameter distributes over the members of a union. Wrap both sides in square brackets when you want to test the union as a whole.

Exercises

Exercises

Work out each type by hand, member by member, then check in the Playground by hovering.

1. Utility, mapped and conditional types

Warm-upComputational

What is Exclude<"a" | "b" | "c", "a">? Write it as TypeScript prints it.

2. Utility, mapped and conditional types

Warm-upComputational

With the lesson's User (id, name, email, city?, joined), which properties does Omit<User, "id" | "joined"> have? List their names.

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

3. Utility, mapped and conditional types

CoreComputational

With type ElementOf<T> = T extends readonly (infer E)[] ? E : never;, which of these statements are true? Choose all that apply.

Choose all that apply

4. Utility, mapped and conditional types

CoreComputational

With type IsString<T> = T extends string ? "yes" : "no";, what is IsString<"x" | 1>? Write it as TypeScript prints it.

5. Utility, mapped and conditional types

CoreComputational

With the lesson's Getters<T> (keys renamed to `get${Capitalize<K>}`), what are the keys of Getters<{ a: 1; bc: 2 }>?

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

6. Utility, mapped and conditional types

CoreComputational

What does the lesson's buildPath("/files/:name", { name: "a b.txt" }) return?

7. Utility, mapped and conditional types

StretchComputational

With type Status = "draft" | "review" | "published" | "archived";, what is Extract<Status, `${string}d`>? Write it as TypeScript prints it.

Further reading and resources