Thuta Learning
TypeScript
AdvancedProgrammingIntermediate

Utility & Mapped Types

TypeScriptLesson 2030 min

What you'll walk away with

  • Write a mapped type using keyof, indexed access T[K] and [K in keyof T]
  • Combine Partial, Required, Readonly, Pick, Omit and Record to build update and form types
  • Change optional, readonly and key names with + / - modifiers and as key remapping
  • Avoid the limits of the built-ins, such as shallow Readonly and typo-blind Omit

Explain it simply

Utility and mapped types in plain language

Think of a formula column in a spreadsheet. Instead of typing values by hand, you say 'take the column on the left and do something to it', and the result updates whenever the source changes. A mapped type is that formula for types: 'take every property of User and make it optional', and the result follows User whenever User changes.

Utility types are the common formulas TypeScript ships with names already attached: Partial, Required, Readonly, Pick, Omit and Record. You write your own mapped type only when none of them fits.

Problem → Why → Solution

The problem: hand-copied types drift apart

Your User type gains an avatarUrl field. The update form type, the validation-error type and the table-column flags were all written by hand as separate types, so none of them learns about the new field. The form silently ignores it, and nothing fails to compile, because each copy is internally consistent; they just disagree with User.

user-types.ts
type User = { id: string; name: string; email: string; avatarUrl: string };

// Hand-written copies, each one a chance to drift:
type UserUpdate = { name?: string; email?: string }; // forgot avatarUrl
type UserErrors = { name?: string; email?: string }; // forgot it here too
type UserFlags = { id: boolean; name: boolean; email: boolean }; // and here

Why this hurts

Every hand-written copy is a second source of truth. TypeScript checks that each value matches its own type, but it cannot know that UserUpdate was supposed to mirror User. Deriving the types (Partial<Omit<User, "id">>, a mapped type over keyof User) makes the relationship explicit, so the compiler updates or flags every dependent type when User changes.

Core concept: walking over keys to build a new type

A mapped type walks over a set of keys and builds a new property for each one. Read { [K in keyof T]: T[K] } as 'for every key K of T, make a property K whose type is T[K]'. keyof T produces the union of T's property names, and T[K] (an indexed access type) looks up the type of one property. Change the right-hand side and every property changes at once: { [K in keyof T]: boolean } turns every field into a flag. All of this happens at compile time: a mapped type emits no JavaScript, so your functions still have to build the resulting objects.

The built-in utility types are just mapped types with names. Partial<T> adds ? to every property, Required<T> removes it, and Readonly<T> adds readonly. Pick<T, K> keeps only the keys in K, Omit<T, K> keeps all the others, and Record<K, V> builds an object type with keys K and values V. Because they compose, Partial<Pick<User, "name" | "email">> means 'an object that may contain name and/or email, and nothing else'.

UtilityResult for User
Partial<User>every property optional
Readonly<User>every property readonly (one level only)
Pick<User, "id" | "name">only id and name
Omit<User, "email">everything except email
Record<"admin" | "guest", User>keys admin and guest, each a User

Mapped types over keyof T are called homomorphic, and they copy the original modifiers: if a property was optional or readonly in T, it stays that way unless you change it. You can add or remove modifiers explicitly with + and -: { -readonly [K in keyof T]: T[K] } makes everything writable, and { [K in keyof T]-?: T[K] } makes everything required, which is exactly how Required<T> is defined.

A mapped type is a formula over keys
  1. Start from one source type
  2. keyof lists its property names
  3. [K in ...] visits each key
  4. Write the new type for each key

Utility types are named mapped types; when the built-ins do not fit, write the mapping yourself.

General pattern

typescript
type Mapped<T> = { [K in keyof T]: NewType };

type Optional<T> = { [K in keyof T]?: T[K] };
type Writable<T> = { -readonly [K in keyof T]: T[K] };
type Renamed<T> = { [K in keyof T as NewKeyName]: T[K] };

type Derived = Partial<Pick<Source, "keyA" | "keyB">>;

[K in keyof T] visits every key and the right-hand type becomes the new property's type. Control ? and readonly with +/-, rename keys with as, and nest the built-ins inside each other to combine them.

Worked example: patches and change flags from one User

Here one User type is the source. UserPatch derives the editable fields as optional, and a custom mapped type, Flags<T>, records which fields changed. The two commented lines at the bottom show mistakes that the derived types prevent.

utility-mapped.ts
type User = { id: string; name: string; email: string };
type UserPatch = Partial<Pick<User, "name" | "email">>;
type Flags<T> = { readonly [K in keyof T]: boolean };

function applyPatch(user: User, patch: UserPatch): User {
  return { ...user, ...patch };
}

function changedFields(before: User, after: User): Flags<UserPatch> {
  return {
    name: before.name !== after.name,
    email: before.email !== after.email,
  };
}

const ada: User = { id: "u1", name: "Ada", email: "ada@old.dev" };
const updated = applyPatch(ada, { email: "ada@new.dev" });
const changed = changedFields(ada, updated);

console.log(updated);
console.log(changed);
// changed.name = false; // error: name is readonly
// applyPatch(ada, { id: "u2" }); // error: id is not part of UserPatch

Code breakdown

  1. Compose utilitiestype UserPatch = Partial<Pick<User, "name" | "email">>;

    Pick keeps only name and email, then Partial makes both optional. There is no way to put id into a patch.

  2. Custom mapped typetype Flags<T> = { readonly [K in keyof T]: boolean };

    For each key of T it creates a readonly boolean. Because it maps over keyof, it also copies UserPatch's ? modifiers.

  3. Merge a patchreturn { ...user, ...patch };

    Only the fields present in the patch override the user's fields, so sending just { email } leaves the name alone.

  4. Return the flagsfunction changedFields(before: User, after: User): Flags<UserPatch> {

    The return type is derived from UserPatch, so the day a field is added to the patch, this object automatically accepts a flag for it.

You should see
{ id: 'u1', name: 'Ada', email: 'ada@new.dev' }
{ name: false, email: true }

Your own mapped types: modifiers and key remapping

When the built-ins are not enough, write the mapping yourself. Mutable<T> strips readonly with -readonly, and Getters<T> renames every key with an as clause and a template literal type: theme becomes getTheme, and its value becomes a function returning T[K].

custom-mapped.ts
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type Settings = { readonly theme: string; readonly fontSize: number };

function makeGetters(settings: Settings): Getters<Settings> {
  return {
    getTheme: () => settings.theme,
    getFontSize: () => settings.fontSize,
  };
}

const draft: Mutable<Settings> = { theme: "dark", fontSize: 14 };
draft.fontSize = 16; // allowed: readonly was removed
const getters = makeGetters(draft);
console.log(getters.getTheme(), getters.getFontSize());

The string & K part is needed because keyof can also produce number and symbol keys, and Capitalize only accepts strings. An as clause that returns never drops that key, which is also how you filter keys out of a mapped type.

In real projects

Derived types in real codebases

Derived types are everywhere in production TypeScript. These are patterns you will meet in almost every codebase:

  • PATCH endpoints and update forms: Partial<Omit<User, "id" | "createdAt">> accepts any subset of the editable fields and rejects attempts to change the id.
  • Form state: a mapped type such as { [K in keyof Form]?: string } holds one optional error message per field, and { [K in keyof Form]: boolean } tracks which fields were touched.
  • Lookup tables: Record<Status, string> for labels or colours forces an entry for every status, so adding a new status breaks the build until the table is updated.
  • Library APIs: ORMs and state libraries use Readonly, Pick and key remapping to generate typed selectors, getters and query results from one model definition.

Common mistakes

Common mistakes with utility and mapped types

Expecting Readonly to be deep

Readonly<Order> stops order.items = [] but not order.items.push(x), because only the top-level properties become readonly. For nested data use readonly arrays such as readonly string[] in the type, or write a recursive DeepReadonly type.

Trusting Omit to catch typos

Omit<User, "emial"> compiles and removes nothing, because Omit accepts any string key. Pick, by contrast, requires keys that exist (K extends keyof T). If you need a typo-safe omit, write type StrictOmit<T, K extends keyof T> = Omit<T, K>.

Assuming Partial blocks undefined

Without the exactOptionalPropertyTypes compiler option, { name: undefined } is a valid Partial<User>, and spreading it over a user overwrites the name with undefined. Strip undefined values before merging, or enable that option.

Best practices

Best practices

  • Keep one source type per domain model and derive form, patch and view types from it.
  • Give derived types names such as UserPatch or UserFormErrors, so error messages stay readable and the purpose is obvious.
  • Prefer a built-in utility type over a custom mapped type when one fits; the whole team recognises it instantly.
  • Avoid nesting utility types more than about three levels deep; when it gets dense, pull the middle step out into a named alias.

Mini challenge

Mini challenge: FormErrors<T> for any form

A sign-up form has username, email and age fields. Build a FormErrors<T> mapped type that holds an optional error message for each field of any form type, then write validateSignUp so that it can only report errors for fields that exist.

  • Define FormErrors<T> with a mapped type over keyof T (each value an optional string)
  • validateSignUp(form: SignUp) returns FormErrors<SignUp>
  • Reject a username under 3 characters, an email without @, and an age under 13
  • Print the errors for one invalid and one valid form
form-errors.ts
type SignUp = { username: string; email: string; age: number };

// TODO: one optional string message per key of T
type FormErrors<T> = unknown;

function validateSignUp(form: SignUp): FormErrors<SignUp> {
  // TODO: collect a message for each invalid field
  return {};
}

// TODO: print the result for an invalid form and a valid form

Expected: The invalid form prints an object with messages for username, email and age; the valid form prints {}. Writing errors.password = "x" is a compile error.

Show hint

Recall how Partial<T> is written: { [K in keyof T]?: T[K] }. Here you only need to change the value type to string. Start the errors object as {} and check each field.

Show solution
form-errors.ts
type SignUp = { username: string; email: string; age: number };

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

function validateSignUp(form: SignUp): FormErrors<SignUp> {
  const errors: FormErrors<SignUp> = {};
  if (form.username.trim().length < 3) errors.username = "At least 3 characters";
  if (!form.email.includes("@")) errors.email = "Must contain @";
  if (form.age < 13) errors.age = "Must be 13 or older";
  // errors.password = "x"; // error: password is not a key of SignUp
  return errors;
}

console.log(validateSignUp({ username: "al", email: "al.example.com", age: 12 }));
console.log(validateSignUp({ username: "alice", email: "alice@example.com", age: 30 }));

Quick quiz 1 / 3

With type Flags<T> = { readonly [K in keyof T]: boolean }, what is Flags<{ name?: string; age: number }>?

Quick quiz 2 / 3

type Order = Readonly<{ id: string; items: string[] }>. For order: Order, which line compiles?

Quick quiz 3 / 3

A PATCH /users/:id handler may change any of name and email, but never id. Which type fits the request body?

What to remember

  • A mapped type { [K in keyof T]: ... } visits every key of T and builds a new type for each property.
  • Partial, Required, Readonly, Pick, Omit and Record are named mapped types, and they compose.
  • Homomorphic mapped types copy ? and readonly; change them with +/- and rename keys with as.
  • Readonly is shallow, Omit does not catch key typos, and Partial still accepts explicit undefined.

Utility Types — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Utility & Mapped Types | Thuta Learning