Skip to content
FrontDepth, Home

TypeScript

Utility, mapped and conditional types

How TypeScript computes types from other types: keyof, typeof and indexed access, the everyday utility types and how they are defined, mapped types with modifiers and key remapping, template literal types, conditional types with infer and distribution, and when type-level code is too clever.

MiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

This topic starts at Middle level.

MiddleConcept

keyof, typeof and indexed access types

Most type transformations start from something that already exists: a value or another type. Three operators let you derive a type instead of writing it a second time.

  • typeof value in a type position gives the type of a variable or property. It is the type-level typeof, not the JavaScript operator that returns "string" at run time, and TypeScript allows it only on identifiers and their properties.
  • keyof T is the union of T's keys.
  • T[K], an indexed access type, is the type of property K. K can be a union, and T[number] gives the element type of an array or a tuple.
TypeScript
const config = {
  apiUrl: "/api",
  retries: 3,
  features: { search: true },
};

type Config = typeof config; // { apiUrl: string; retries: number; features: { search: boolean } }
type ConfigKey = keyof typeof config; // "apiUrl" | "retries" | "features"
type Features = Config["features"]; // { search: boolean }
type Scalar = Config["apiUrl" | "retries"]; // string | number

One list, one source of truth

A common pattern: keep the allowed values in code, where the program can use them at run time, and derive the type from them.

TypeScript
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"

function isRole(value: string): value is Role {
  return (ROLES as readonly string[]).includes(value);
}

Without as const, ROLES would be a string[] and Role would be plain string. Add "owner" to the array and the type follows; a hand-written union would drift away from the array. isRole is a built on the same list, so the check and the type cannot disagree.

Objects work the same way. With const STATUS = { active: "Active", banned: "Banned" } as const, keyof typeof STATUS is "active" | "banned", and (typeof STATUS)[keyof typeof STATUS] is "Active" | "Banned".

Values and types live in different places

Indexed access takes types, not values:

TypeScript
const key = "retries";
type Retries = Config[key]; // Error: Type 'key' cannot be used as an index type.
type Retries2 = Config[typeof key]; // number

And typeof does not run code: typeof createUser("Aysel") is a syntax error. The type of a call's result is ReturnType<typeof createUser>, one of the utility types below.

These three operators are the building blocks of everything else in this topic: the built-in utility types are written with keyof and indexed access.

MiddleConcept

Everyday utility types

are generic types from TypeScript's standard library that build one type from another. They are global, so there is nothing to import. The ones you meet every day:

TypeScript
type User = {
  id: string;
  name: string;
  email?: string;
  readonly createdAt: Date;
};

type UserPatch = Partial<Omit<User, "id" | "createdAt">>; // { name?: string; email?: string }
type CompleteUser = Required<User>; // email is no longer optional
type UserPreview = Pick<User, "id" | "name">; // { id: string; name: string }
type FrozenUser = Readonly<User>; // every property readonly
type CountByStatus = Record<"draft" | "published", number>; // { draft: number; published: number }
type Name = NonNullable<string | null | undefined>; // string
  • Partial<T> makes every property optional: update payloads, form drafts, overrides in test factories.
  • Required<T> removes ? from every property: a config after the defaults have been filled in.
  • Readonly<T> marks every property readonly: data you pass around but must not change. It exists only for the type checker; it does not freeze the object.
  • Pick<T, K> keeps the listed keys, Omit<T, K> keeps all the others. Pick gives a small view of a big type; Omit gives "the same thing without the fields the server generates".
  • Record<K, V> is an object type with keys K and values V. With a union of literal keys every key is required, which makes it a good exhaustive lookup table.
  • NonNullable<T> removes null and undefined.

An exhaustive lookup table

TypeScript
type Status = "draft" | "review" | "published";

const statusLabel: Record<Status, string> = { // Error
  draft: "Draft",
  review: "In review",
};

The error says "Property 'published' is missing in type '{ draft: string; review: string; }' but required in type 'Record<Status, string>'." Add a status to the union, and every Record<Status, …> in the codebase stops compiling until it handles the new case. A plain object typed { [key: string]: string } would never tell you.

Compose, then name the result

Utility types nest. Partial<Omit<User, "id" | "createdAt">> reads from the inside out: "a User without id and createdAt, everything optional". When the result is used in more than one place, give it a name such as UserPatch, so hovers and error messages show the name instead of the expression.

The point of all of them is that the derived type follows the original. Add phone?: string to User, and UserPatch accepts a phone too, while UserPreview stays as it is because it lists its keys. A copied type would stay behind silently.

MiddleConcept

Types from functions: ReturnType, Parameters, Awaited

When a function already defines a shape, derive the type from the function instead of declaring it twice. These utilities take a function type, so you pass them typeof fn:

TypeScript
function createCart(ownerId: string, currency: "AZN" | "EUR" = "AZN") {
  return { ownerId, currency, items: [] as CartItem[], createdAt: new Date() };
}

type Cart = ReturnType<typeof createCart>;
// { ownerId: string; currency: "AZN" | "EUR"; items: CartItem[]; createdAt: Date }

type CartArgs = Parameters<typeof createCart>;
// [ownerId: string, currency?: "AZN" | "EUR"]

type Currency = Parameters<typeof createCart>[1]; // "AZN" | "EUR" | undefined

Parameters gives a tuple, so you index it with a number to get one parameter. Optional parameters stay optional, which is why Currency includes undefined.

Awaited for async functions

The return type of an async function is a Promise. Awaited<T> unwraps it the way await does: recursively, and leaving values that are not promises alone.

TypeScript
async function loadDashboard(userId: string) {
  const [user, orders] = await Promise.all([getUser(userId), getOrders(userId)]);
  return { user, orders };
}

type DashboardPromise = ReturnType<typeof loadDashboard>; // Promise<{ user: User; orders: Order[] }>
type Dashboard = Awaited<ReturnType<typeof loadDashboard>>; // { user: User; orders: Order[] }

type Nested = Awaited<Promise<Promise<number>>>; // number
type Mixed = Awaited<boolean | Promise<number>>; // number | boolean

When to reach for them

  • A library function whose return type is not exported: ReturnType<typeof createClient> instead of copying its shape.
  • A wrapper that passes arguments through unchanged: function withRetry(...args: Parameters<typeof send>).
  • A factory or a store whose shape is defined by the code that builds it.

Two caveats. For an overloaded function, ReturnType and Parameters see only the last signature, as the handbook notes; they cannot pick an overload for you. And a type derived from an implementation changes whenever the implementation does, without anyone deciding it should. For an internal helper that is convenient. For a function other modules depend on, an explicit, named return type is a contract you change on purpose, and a change in the body that breaks it fails where it was made.

MiddleConcept

Mapped types

A builds an object type by iterating over a union of keys, the way map iterates over an array. Partial, Required, Readonly, Pick and Record are all mapped types. This is how the standard library defines three of them:

TypeScript
type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };

Read [P in keyof T]: T[P] as "for each key P of T, a property P of the same type". The pieces:

  • P in Keys iterates over a union: keyof T, or any union of string literals, as Record<K, T> does with [P in K]: T.
  • ? and readonly add a modifier to every property. A - prefix removes it instead: -? makes properties required, -readonly makes them writable. No prefix means +.
  • When the keys come from keyof T, the existing modifiers are kept. Mapping over a type with an optional email keeps email optional unless you write -?.
TypeScript
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

type FieldErrors<T> = { [K in keyof T]?: string };
type SignupErrors = FieldErrors<{ email: string; password: string }>;
// { email?: string; password?: string }

Key remapping with as

Since TypeScript 4.1, an as clause renames keys while mapping. With a template literal type it can generate new names:

TypeScript
type Getters<T> = {
  [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};

type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

keyof T & string keeps only the string keys, because Capitalize needs a string and keyof may also contain number and symbol keys.

Remapping a key to never drops it, which turns a mapped type into a filter:

TypeScript
type StringFields<T> = {
  [K in keyof T as T[K] extends string ? K : never]: T[K];
};

type Text = StringFields<{ id: number; title: string; body: string }>;
// { title: string; body: string }

T[K] extends string ? K : never is a conditional type: it keeps the key when the property is a string and gives never otherwise.

Mapped types are the right tool when one type must follow another key by key: errors per form field, a handler per event, a loading flag per resource. If you only need a few fixed keys, write them out.

MiddlePitfalls

Pitfalls of the built-in utility types

The built-in utility types are short definitions, and their edge cases follow from those definitions.

Omit does not check its keys

TypeScript
type Post = { id: string; title: string; publishedAt: Date };

type Draft = Omit<Post, "publishedAtt">; // no error: still has publishedAt
type Preview = Pick<Post, "titel">; // Error: Type '"titel"' does not satisfy the constraint 'keyof Post'.

Pick<T, K extends keyof T> checks the keys; Omit<T, K extends keyof any> accepts any string, so a typo or a renamed field removes nothing and nobody notices. If your codebase wants the check, a one-line type StrictOmit<T, K extends keyof T> = Omit<T, K> adds it.

Pick and Omit flatten unions

TypeScript
type Shape =
  | { kind: "circle"; radius: number; id: string }
  | { kind: "square"; size: number; id: string };

type NewShape = Omit<Shape, "id">; // { kind: "circle" | "square" }

keyof of a union contains only the keys all members share, so Omit keeps kind and loses radius and size. The is gone. Apply Omit to each member instead, with a conditional type that runs once per member of the union:

TypeScript
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;

type NewShape2 = DistributiveOmit<Shape, "id">;
// { kind: "circle"; radius: number } | { kind: "square"; size: number }

Readonly is shallow and only a type

Readonly<Settings> stops settings.theme = "light", but settings.tags.push("x") still compiles, because the array inside is not readonly. Nothing changes at run time either: the object is not frozen, and code that receives it as a plain Settings can modify it. Use readonly string[] or ReadonlyArray for nested arrays, and Object.freeze when you need run-time protection (it is shallow too).

Partial accepts undefined

Even under strict, Partial<User> accepts { email: undefined }. Spread into a user, it overwrites the email with undefined, and the result is still typed User. The exactOptionalPropertyTypes option, which strict does not include, makes "missing" and "undefined" different, so that call stops compiling.

Record<string, T> claims every key exists

const prices: Record<string, number> makes prices["pear"] a number, even when there is no pear. Use Partial<Record<string, number>> (reads give number | undefined), a Map, or turn on noUncheckedIndexedAccess.

SeniorConcept

Template literal types

Template literal types use JavaScript's template string syntax in type positions. With literal types they build new literals; with unions they build every combination:

TypeScript
type Size = "sm" | "md" | "lg";
type Tone = "primary" | "danger";

type ButtonClass = `btn-${Tone}-${Size}`;
// "btn-primary-sm" | "btn-primary-md" | "btn-primary-lg" | "btn-danger-sm" | ...

type Px = `${number}px`;
const width: Px = "12px"; // OK
const height: Px = "12em"; // Error: Type '"12em"' is not assignable to type '`${number}px`'.

type UserPath = `/users/${string}`;

${number} and ${string} are patterns: any number, any string. Unions in several positions are cross-multiplied, as ButtonClass shows: 2 tones times 3 sizes is 6 members.

TypeScript also has four built-in string types that the compiler implements itself: Uppercase, Lowercase, Capitalize and Uncapitalize. They make naming conventions checkable:

TypeScript
type HandlerName<E extends string> = `on${Capitalize<E>}`;
type Handlers = HandlerName<"click" | "focus">; // "onClick" | "onFocus"

Taking strings apart with infer

In a conditional type, a template literal works as a pattern, and infer captures the parts. This type reads the parameter names out of a route path, the way typed routers do:

TypeScript
type RouteParams<S extends string> =
  S extends `${string}:${infer Param}/${infer Rest}`
    ? Param | RouteParams<`/${Rest}`>
    : S extends `${string}:${infer Param}`
      ? Param
      : never;

type Params = RouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"
type None = RouteParams<"/about">; // never

It is recursive: each step takes the first :param and calls itself on the rest of the path.

Keep the unions small

Cross-multiplication grows fast. Three positions with ten options each give 1,000 members, and the checker compares values against all of them. Past a limit, TypeScript gives up with "Expression produces a union type that is too complex to represent." The handbook recommends generating large string unions ahead of time instead of computing them in types, and template literal types are at their best with a handful of members: class name variants, event and handler names, route patterns, CSS units.

SeniorConcept

Conditional types and infer

A chooses between two types: T extends U ? X : Y is X when T is assignable to U, and Y otherwise. With a concrete type it resolves at once; with a type parameter it waits until the parameter is known.

TypeScript
type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<"hello">; // "yes"
type B = IsString<number>; // "no"

On its own that is a type-level if. Conditional types become useful with infer.

infer: pattern matching on types

Inside the extends clause, infer X declares a type variable that TypeScript fills in from the match. This is how the standard library takes types apart:

TypeScript
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

"If T is a function, call its return type R and give me R." The same pattern works for your own types:

TypeScript
type ElementType<T> = T extends readonly (infer U)[] ? U : T;
type E1 = ElementType<string[]>; // string
type E2 = ElementType<string>; // string

type PropsOf<C> = C extends (props: infer P) => unknown ? P : never;
type ButtonProps = PropsOf<typeof Button>; // the props type of a function component

type Unwrap<T> = T extends Promise<infer V> ? V : T;
type U1 = Unwrap<Promise<Promise<number>>>; // Promise<number>: one level only

Unwrap stops after one level because it does not call itself; the built-in Awaited is recursive, so Awaited<Promise<Promise<number>>> is number.

The limit: generic functions with conditional return types

A conditional return type looks like a precise signature, but the body cannot satisfy it:

TypeScript
function label<T extends string | number>(value: T): T extends string ? "text" : "number" {
  return typeof value === "string" ? "text" : "number"; // Error: Type '"text"' is not assignable to type 'T extends string ? "text" : "number"'.
}

typeof value === "string" narrows value, not T, so TypeScript cannot decide which branch applies and the type stays unresolved inside the function. The usual answers are function overloads, one per case, or a single assertion in a well-tested place. For a function this small, ask whether callers need the precision at all; a return type of "text" | "number" is honest and needs no tricks.

SeniorConcept

Distribution over unions

When the checked type is a bare type parameter and you pass it a union, a conditional type is applied to each member separately, and the results are joined into a new union:

TypeScript
type ToArray<T> = T extends unknown ? T[] : never;

type A = ToArray<string | number>; // string[] | number[], not (string | number)[]

The handbook calls this a distributive conditional type, and it is what makes Exclude and Extract work:

TypeScript
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;

type Events = "click" | "focus" | "blur";
type NoBlur = Exclude<Events, "blur">; // "click" | "focus"

Each member is checked on its own; the ones that map to never disappear, because never is the empty union.

Turning it off

Distribution happens only when the checked type is a naked type parameter. Wrap both sides of extends in a one-element tuple to check the union as a whole:

TypeScript
type ToArrayAll<T> = [T] extends [unknown] ? T[] : never;
type B = ToArrayAll<string | number>; // (string | number)[]

type IsString<T> = T extends string ? "yes" : "no";
type IsOnlyString<T> = [T] extends [string] ? "yes" : "no";

type C = IsString<string | number>; // "yes" | "no"
type D = IsOnlyString<string | number>; // "no"

Two surprises

  • boolean is true | false, so it distributes too: boolean extends true ? … : … in a distributive position gives both branches.
  • never is an empty union, so distributing over it gives never, not either branch:
TypeScript
type IsNever<T> = T extends never ? true : false;
type E = IsNever<never>; // never

type IsNeverFixed<T> = [T] extends [never] ? true : false;
type F = IsNeverFixed<never>; // true

Which one you want

Distribution is right when you transform each member: Exclude, Extract, an Omit that keeps a discriminated union intact, a handler type per event. Wrap the parameter in [ ] when you ask a question about the type as a whole: is it never, is it exactly string, is it a union at all. Many confusing results from hand-written conditional types come from forgetting which of the two a type does; when a result surprises you, check whether the checked type is a bare type parameter.

SeniorPitfalls

When type-level code is too clever

Type-level code is code. Someone has to read it, the compiler has to run it, and the errors it produces land on other people. Correct types can still be a bad trade.

What it costs

  • Readability. This type produces every dotted path of an object, such as "a" | "a.b" | "a.b.c":
TypeScript
type Paths<T> = T extends object
  ? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
  : never;

It uses a conditional type, a mapped type, indexed access, a template literal and recursion at once. Most teammates can call it; few can change it safely.

  • Error messages. A wrong call reports the computed type, not the intent: passing "a.b.x" where a Paths<Config> is expected fails because it is not assignable to the union of every valid path. For a small config that is fine; for a large one the message is a wall of paths.
  • Compile time and limits. Every instantiation is work for the checker, and the editor repeats it on every keystroke. Deep recursion stops with "Type instantiation is excessively deep and possibly infinite." tsc --extendedDiagnostics prints the instantiation count and check time, and tsc --generateTrace <dir> writes a trace that shows which types are slow.
  • False confidence. A computed type describes what the runtime code should do; the link between them is often a cast such as return out as Getters<T>, and nothing checks it. A mistake in the implementation stays invisible behind a precise-looking type.

What to do instead

  • Ask which bug the type prevents. If a hand-written union of five routes, a plain string plus one run-time check, or a named object type catches the same mistakes, prefer it.
  • Keep advanced types in one place, usually a shared module or a library boundary, and let application code use them by name.
  • Name the intermediate steps (type Keys = …, type Mapped = …) instead of nesting everything in one expression, and leave a comment with an example of the input and the output.
  • Test the types: calls that must compile and calls marked // @ts-expect-error that must not, checked by tsc in CI. Test the run-time code behind a cast as well.

A line that works for many teams, and it is a judgement call rather than a rule of the language: precise types at the edges, where they catch real mistakes, and simple types in the middle, where people read and change code every day.

SeniorInterview tips

Interview tips

A 30-second answer. "TypeScript can compute types from other types. typeof, keyof and indexed access derive types from values and from each other. Utility types like Partial, Pick, Omit, Record and ReturnType are generic types in the standard library, mostly mapped types: they iterate over keys and can add or remove readonly and ?, or rename keys with as. Conditional types choose a type with T extends U ? X : Y, infer pulls types out of a match, and over a union they distribute member by member unless you wrap the parameter in a tuple. I use them to keep one source of truth, and I keep them simple enough for the team to read."

Questions you are likely to get

  • Implement Partial, Readonly, Pick or Record. A mapped type over keyof T (or K) with the right modifier; Pick needs K extends keyof T.
  • Implement ReturnType, Parameters or an ElementType. A conditional type with infer in the matched position.
  • What is the difference between Pick and Omit? Beyond "keep vs remove": Omit does not check its keys, and both flatten unions.
  • What does IsString<string | number> give, and why? Both branches, because the conditional type distributes; [T] extends [string] checks the union as a whole.
  • How do you get a union type from an array of values? as const plus (typeof ARR)[number].
  • What is Awaited for? The value type of a promise, unwrapped recursively, typically Awaited<ReturnType<typeof fn>> for an async function.

Mistakes that cost points

  • Treating Readonly<T> as immutability: it is shallow and has no run-time effect.
  • Using Omit on a discriminated union and wondering where the variant fields went.
  • Forgetting as const, then wondering why the derived type is string.
  • Writing a deeply recursive type where a hand-written union of five members would do.
  • Not knowing that never distributes to never.

Senior signal

Talk about trade-offs. Show that you derive types instead of copying them, and that you also know when deriving couples too much: an exported API deserves a named, explicit type. Mention the costs of clever types (unreadable errors, checker time, the cast that links the type to the runtime) and how you would contain them: one module, named intermediate types, type tests in CI. If you can write DistributiveOmit, explain in one sentence why it needs T extends unknown.

MiddleReview checklist

What to check when reviewing type transformations

Use this list when you review types you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Derived and computed types fail quietly; the cost shows up later, as a type that no longer matches the data or an error message nobody can read.

  • Is the type derived from its source, or copied from it? A hand-written copy of an API type, a function's return value or a list of allowed values drifts as soon as the original changes. Look for typeof, keyof, ReturnType and as const arrays where a second definition appears.
  • Do the keys passed to Omit exist? Omit accepts any string, so a typo or a renamed field removes nothing. Hover the result in the editor, or use Pick or a key-checked Omit, which reject unknown keys.
  • Is Omit or Pick applied to a union? They keep only the keys all members share, so a discriminated union collapses into one object without its variant fields. Hover the result; use a distributive version when it should stay a union.
  • Does Readonly or Partial promise more than it delivers? Readonly is shallow and does nothing at run time; Partial lets callers pass undefined explicitly. Check nested arrays and objects, and what a spread of a partial object does to required fields.
  • Is a computed type connected to the runtime code by a cast? Mapped types with renamed keys and conditional return types often end in as SomeType. Read the implementation next to the type, or run it, and check that the produced keys and values really match.
  • Does a conditional type distribute when it should not, or the other way round? Feed it a union and never in a quick type test: a "question" type like IsString usually needs [T] extends [U].
  • Can a teammate read the type and the errors it produces? Make a deliberate mistake at a call site and read the message. If it is a wall of generated members, or tsc --extendedDiagnostics shows the instantiation count jumping, simplify or name the steps.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions