Skip to content

TypeScript type operators, conditional and mapped types

Once a codebase has a few core types, most other types should be derived from them rather than written again by hand. An update form needs the order type with every field optional; an event system needs one handler name per event; an API client needs the result type of each endpoint function. If those are separate hand-written types, they drift. This hub covers TypeScript’s type-level tools for deriving types: the type operators keyof, typeof and indexed access, conditional types with infer, mapped types and template literal types.

These are the features the built-in utility types are written with, so this hub also explains how Partial, Exclude and ReturnType work. Read Generics and functions first; every feature here is used with type parameters.

All samples are complete ES modules from an invented online shop, OrdersPortal, compiled with TypeScript 7.0.2 (tsc --strict --target es2025 --module nodenext) and run with Node.js 22. Save one as sample.ts next to a package.json containing {"type": "module"}, then run npx tsc --strict sample.ts and node sample.js. Type-level results are shown in comments; where a sample prints, its output follows it.

Topic Since Use it when
Type operators keyof and indexed access 2.1 You need the keys, the type of a value, or the type of a property.
Conditional types TypeScript 2.8 A type depends on another type, or you extract part of a type.
Mapped types 2.1; key remapping 4.1 You transform every property of an object type.
Template literal types TypeScript 4.1 String types follow a pattern or are built from other strings.

TypeScript 2.1 added keyof and indexed access types; the typeof type query is older. Together they let you read types off existing types and values:

  • keyof T is the union of T’s property names: keyof Order is "id" | "status" | "total".
  • T[K] is the type of property K of T: Order["status"]. With a union of keys it gives a union of property types, and indexing an array type with number gives its element type: Order[][number] is Order.
  • typeof value, in a type position, is the type of a variable or property. It turns values you already have, such as a configuration object or a function, into types, so the value stays the single source of truth.

These three are the glue of type-level code. Combined with as const, they let you declare data once and derive the matching types, as in the sample: the list of supported currencies is an array value, and the Currency type comes from it.

const CURRENCIES = ["EUR", "USD", "GBP"] as const;
type Currency = (typeof CURRENCIES)[number]; // "EUR" | "USD" | "GBP"
interface Order {
id: string;
status: "pending" | "paid" | "shipped";
total: number;
currency: Currency;
}
type OrderKey = keyof Order; // "id" | "status" | "total" | "currency"
type OrderStatus = Order["status"]; // "pending" | "paid" | "shipped"
type IdOrTotal = Order["id" | "total"]; // string | number
const defaults = { status: "pending", currency: "EUR" } satisfies Partial<Order>;
type Defaults = typeof defaults; // { status: "pending"; currency: "EUR" }
function field<K extends OrderKey>(order: Order, key: K): Order[K] {
return order[key];
}
const order: Order = { id: "ORD-1", total: 40, ...defaults };
const status: OrderStatus = field(order, "status");
const total: IdOrTotal = field(order, "total");
const keys: OrderKey[] = ["id", "status", "total", "currency"];
console.log(status, total, keys.length, CURRENCIES.includes(order.currency));

Output:

pending 40 4 true

Pitfalls:

  • keyof on an index signature is wide. For { [key: string]: number }, keyof is string | number, because numeric keys are allowed too.
  • typeof in an expression is the JavaScript operator. typeof x === "string" is a runtime check; type T = typeof x is a type query. The position decides which one you get.

Conditional types arrived in TypeScript 2.8. T extends U ? X : Y is a type-level if: if T is assignable to U, the result is X, otherwise Y. Inside the extends clause, infer R declares a type variable that the compiler fills in by matching, which is how you extract part of a type: the element type of an array, the resolved type of a promise, the return type of a function.

When the checked type is a naked type parameter and you pass a union, the conditional type is distributive: it is applied to each member separately and the results are joined. Exclude<T, U> (T extends U ? never : T) relies on this to drop members from a union, because never disappears from a union. Wrap both sides in brackets, [T] extends [U], to turn distribution off.

Conditional types power Exclude, Extract, NonNullable, ReturnType, Parameters and Awaited in the standard library. Writing your own is worth it when the same derivation appears in several places; for a one-off, a hand-written type is easier to read.

type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type ResultOf<F> = F extends (...args: never[]) => Promise<infer R> ? R : never;
type NonEmptyString<T> = T extends "" ? never : T;
async function loadOrder(id: string) {
return { id, total: 59.9, lines: [{ sku: "SKU-RED-01", quantity: 2 }] };
}
type LoadedOrder = ResultOf<typeof loadOrder>; // { id: string; total: number; lines: ... }
type Line = ElementOf<LoadedOrder["lines"]>; // { sku: string; quantity: number }
type Tag = NonEmptyString<"" | "gift" | "fragile">; // "gift" | "fragile" (distributed)
// Distribution is usually what you want, but not always:
type IsString<T> = T extends string ? "yes" : "no";
type IsStringStrict<T> = [T] extends [string] ? "yes" : "no";
type A = IsString<string | number>; // "yes" | "no"
type B = IsStringStrict<string | number>; // "no"
function lineSummary(line: Line): string {
return `${line.quantity} x ${line.sku}`;
}
const tags: Tag[] = ["gift", "fragile"];
const a: A = "no";
const b: B = "no";
const order: LoadedOrder = await loadOrder("ORD-1");
console.log(order.lines.map(lineSummary).join(", "), tags.join("+"), a, b);

Output:

2 x SKU-RED-01 gift+fragile no no

Pitfalls:

  • Unexpected distribution. IsString<string | number> is "yes" | "no", not "no". Use the bracketed form when you mean “the whole union”.
  • Deep recursion gets slow. Recursive conditional types (supported since TypeScript 4.1) can hit the instantiation depth limit (error TS2589: Type instantiation is excessively deep and possibly infinite.) and slow down the editor. Keep them shallow.

Mapped types arrived in TypeScript 2.1. { [K in keyof T]: X } builds a new object type with one property for every key of T, where X can use K and T[K]. It is a loop over keys at the type level. Modifiers can be added or removed: readonly and ? add them, -readonly and -? (TypeScript 2.8) remove them, which is exactly how Readonly<T>, Partial<T> and Required<T> are defined.

TypeScript 4.1 added key remapping with as: { [K in keyof T as NewKey]: X }. The new key can be computed with a template literal type, and mapping a key to never removes it, which lets one mapped type filter properties by their value type.

Mapped types are homomorphic when they map over keyof T directly: they keep the original properties’ optional and readonly modifiers. That is usually what you want for transformations of an existing type.

interface Order {
readonly id: string;
status: "pending" | "paid" | "shipped";
total: number;
note?: string;
}
// The same definitions as the built-ins, written out.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
// Key remapping: one validator per field, named after the field.
type Validators<T> = {
[K in keyof T as `validate${Capitalize<string & K>}`]: (value: T[K]) => boolean;
};
// Filtering: keep only the numeric fields.
type NumericFields<T> = { [K in keyof T as T[K] extends number ? K : never]: T[K] };
const patch: MyPartial<Order> = { status: "paid" };
const draft: Mutable<Order> = { id: "ORD-1", status: "pending", total: 40 };
draft.id = "ORD-1A"; // allowed: readonly was removed
const validators: Validators<Pick<Order, "status" | "total">> = {
validateStatus: (s) => s !== "shipped",
validateTotal: (t) => t > 0,
};
const numbers: NumericFields<Order> = { total: 40 };
console.log({ ...draft, ...patch });
console.log(validators.validateStatus(draft.status), validators.validateTotal(-1), Object.keys(numbers));

Output:

{ id: 'ORD-1A', status: 'paid', total: 40 }
true false [ 'total' ]

Pitfalls:

  • string & K is needed for template keys. keyof T can include number and symbol keys; Capitalize<K> accepts only strings, so intersect with string first, as in the sample.
  • Mapped types are not deep. Partial<Order> makes order.lines optional, not each line’s fields. A recursive DeepPartial is possible, but check whether the API really needs it.

Template literal types arrived in TypeScript 4.1. They use JavaScript’s template literal syntax at the type level: `order.${"created" | "paid"}` is the union "order.created" | "order.paid". When placeholders hold unions, the result is every combination, so two unions of 3 and 4 members produce 12 strings. A placeholder can also be a wide type, as in `ORD-${number}`, which describes a pattern rather than a finite list.

TypeScript 4.1 also added four intrinsic string types, Uppercase, Lowercase, Capitalize and Uncapitalize, and template literal types can be matched with infer in a conditional type to parse strings at the type level. Typical uses are event names derived from entity and action names, typed route parameters, CSS-like tokens and ID formats.

Template literal types are checked only at compile time. A string from user input or an API is plain string until you check it with a type guard.

type Entity = "order" | "customer";
type Action = "created" | "updated";
type EventName = `${Entity}.${Action}`; // 4 combinations
type OrderId = `ORD-${number}`;
type HandlerName<E extends string> = `on${Capitalize<E>}`;
// Parse route parameters out of a path, at the type level.
type RouteParams<P extends string> = P extends `${string}:${infer Name}/${infer Rest}`
? Name | RouteParams<Rest>
: P extends `${string}:${infer Name}`
? Name
: never;
type OrderLineParams = RouteParams<"/orders/:orderId/lines/:lineId">; // "orderId" | "lineId"
function isOrderId(value: string): value is OrderId {
return /^ORD-\d+$/.test(value);
}
const listeners = new Map<EventName, string[]>();
function on(event: EventName, handler: HandlerName<Action>): void {
listeners.set(event, [...(listeners.get(event) ?? []), handler]);
}
on("order.created", "onCreated");
on("customer.updated", "onUpdated");
const params: Record<OrderLineParams, string> = { orderId: "ORD-1042", lineId: "3" };
console.log([...listeners.keys()], isOrderId(params.orderId), isOrderId("1042"));

Output:

[ 'order.created', 'customer.updated' ] true false

Calling on("order.deleted", "onCreated") fails with error TS2345: Argument of type '"order.deleted"' is not assignable to parameter of type '"customer.created" | "customer.updated" | "order.created" | "order.updated"'.

Pitfalls:

  • Combinations multiply. A template with several large unions can produce thousands of members and slow the compiler. Three placeholders of 50 members each (125,000 combinations) already fail with error TS2590: Expression produces a union type that is too complex to represent.
  • `ORD-${number}` accepts more than you think. "ORD-1.5" and "ORD-1e3" match too, because number includes them; validate the exact format at run time.
  • To read keys or property types from a type, use keyof and T[K]; to get a type from a value, use typeof.
  • To extract part of a type, or choose between types, use a conditional type with infer.
  • To transform every property of a type, use a mapped type; use as to rename or filter keys.
  • To describe string patterns or derive names from other names, use template literal types.
  • Before writing your own, check the built-in utility types; most everyday transformations already exist.

What does keyof return for interface Order { id: string; total: number }, and for Record<string, number>? For the interface, the union "id" | "total". For a string index signature, string | number, because JavaScript converts numeric keys to strings, so numeric access is allowed too.

What is a distributive conditional type? A conditional type whose checked type is a naked type parameter. When that parameter is a union, the conditional type is applied to each member and the results are unioned. Exclude<"a" | "b", "a"> works this way. Wrapping in a tuple, [T] extends [U], disables distribution.

How is Partial<T> defined, and what does -? do? Partial<T> is { [K in keyof T]?: T[K] }, a homomorphic mapped type that adds ? to every property. -? removes optionality instead and is how Required<T> is defined; -readonly removes readonly.

How would you rename every key of a type to getX form? With mapped-type key remapping and a template literal type: { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] }. The string & K excludes number and symbol keys, which Capitalize does not accept.

What is infer used for? It declares a type variable inside the extends clause of a conditional type, which the compiler fills in by pattern matching. T extends Promise<infer R> ? R : T extracts the resolved type of a promise.

Senior scenario: OrdersPortal’s event bus has 60 hand-written event name strings and handler interfaces, and two of them have drifted from the payload types. How would you use the type system to fix this? Define one map type from event name to payload, interface EventPayloads { "order.created": Order; ... }, and derive everything else from it: the event name union with keyof EventPayloads, the emit<E extends keyof EventPayloads>(name: E, payload: EventPayloads[E]) signature, and the handler map with a mapped type. A missing or mismatched payload is then a compile error at every emit and subscribe site. Keep the derived types simple enough to read in editor tooltips, and validate payloads at the process boundary, because these types do not exist at run time.