Indexed access types

Topic 2 of 6 in Type operators6 min readIntermediateFree course

Overview

Big types — API responses, database rows, configuration schemas — often contain smaller types you want to use on their own: the customer inside an order, one line item, the status union. Copying those parts by hand creates duplicates that drift. Indexed access types look them up instead, using the same square-bracket syntax you use on objects.

Indexed access types. Given type User = { name: string; address: { city: string; zip: string }; roles: (“admin” | “editor”)[] }: User[“name”] is string; User[“address”] is { city: string; zip: string }; User[“address”][“city”] is string; User[“roles”][number] is “admin” | “editor”; User[“name” | “roles”] is string | (“admin” | “editor”)[]. Square brackets on a type look up the type of a property — just like obj[“key”] does for values. [number] gives the element type of an array; it works for tuples too.

Looking up a property type

TypeScript
type User = {
  id: number;
  name: string;
  address: { city: string; postcode: string };
  roles: ("admin" | "editor" | "viewer")[];
};

type UserId = User["id"];             // number
type Address = User["address"];       // { city: string; postcode: string }
type City = User["address"]["city"];  // string

The key inside the brackets is a type, so it’s written as a string literal type: User["id"], not User.id (dot syntax doesn’t work for types).

Looking up a key that doesn’t exist is an error:

TypeScript
type Phone = User["phone"];
// error TS2339: Property 'phone' does not exist on type 'User'.

Element types: [number]

Arrays are indexed by numbers, so [number] gives the type of an element:

TypeScript
type Role = User["roles"][number];      // "admin" | "editor" | "viewer"

type Scores = number[];
type Score = Scores[number];            // number

type Entry = [name: string, score: number];
type First = Entry[0];                  // string
type Any = Entry[number];               // string | number

You’ve already used this with as const arrays: (typeof SIZES)[number].

Indexing with unions

Put a union of keys in the brackets, and you get the union of their types:

TypeScript
type IdOrName = User["id" | "name"];    // number | string
type AnyValue = User[keyof User];       // every property type, as a union

T[keyof T] — “the type of any property of T” — is a common building block, as in (typeof Status)[keyof typeof Status] from Enums and alternatives.

With generics

Indexed access is what makes K extends keyof T useful: T[K] is the type of whatever key was passed:

TypeScript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

getProp(user, "roles");   // ("admin" | "editor" | "viewer")[]

You can also index type parameters in generic types:

TypeScript
type ElementOf<T extends readonly unknown[]> = T[number];
type Value<T> = T[keyof T];

Naming the parts of a big type

A typical use — a generated or documented API type, and the pieces your code needs:

TypeScript
type OrderResponse = {
  id: string;
  status: "pending" | "paid" | "shipped";
  customer: { name: string; address: { city: string; country: string } };
  items: { sku: string; quantity: number; unitPrice: number }[];
};

type Customer = OrderResponse["customer"];
type LineItem = OrderResponse["items"][number];
type OrderStatus = OrderResponse["status"];

function lineTotal(item: LineItem) {
  return item.quantity * item.unitPrice;
}

When the API adds a field to line items, LineItem includes it automatically.

Optional properties and indexed access

Indexing an optional property includes undefined:

TypeScript
type Profile = { bio?: string };
type Bio = Profile["bio"];    // string | undefined

To strip it, use the NonNullable utility: NonNullable<Profile["bio"]> is string.

Indexed access vs separate declarations

Should you write type Address = { … } and use it inside User, or define User in one piece and derive User["address"]? Both are fine:

  • Declare small types and compose them when you own the data model — the names show up nicely in errors and hovers.
  • Derive with indexed access when the big type comes from elsewhere (an API client, a code generator, a library) and you can’t or shouldn’t restructure it.

Remember: square brackets on a type look up a property’s type. T["key"] for one property, T[number] for array elements, T[keyof T] for any property.

Exercise

Types from an API response

You get one big OrderResponse type from an API and must not copy any part of it by hand. Using indexed access types, derive: Customer (the customer object), Address (the customer’s address), LineItem (one element of items), Status (the status union) and Currency (the currency of total). Then write shippingLabel(customer: Customer): string (Asha Rao, Pune IN), lineTotal(item: LineItem): number, and isOpen(status: Status): boolean (pending or paid). Use them on the sample order and print the label, the sum of the line totals, and whether the order is open. Show with // @ts-expect-error that isOpen("lost") is rejected.

TypeScript
type OrderResponse = {
  id: string;
  status: "pending" | "paid" | "shipped" | "cancelled";
  customer: {
    name: string;
    email: string;
    address: { city: string; country: string; postcode: string };
  };
  items: { sku: string; quantity: number; unitPrice: number }[];
  total: { amount: number; currency: "USD" | "EUR" | "INR" };
};

// Derive Customer, Address, LineItem, Status, Currency

// shippingLabel, lineTotal, isOpen

const order: OrderResponse = {
  id: "o-1001",
  status: "paid",
  customer: { name: "Asha Rao", email: "asha@example.com", address: { city: "Pune", country: "IN", postcode: "411001" } },
  items: [
    { sku: "LMP-01", quantity: 2, unitPrice: 24.99 },
    { sku: "NB-A5", quantity: 4, unitPrice: 3.5 },
  ],
  total: { amount: 63.98, currency: "INR" },
};

Summary

  • T["key"] is the type of property key on type T — like obj["key"] for values.
  • Chain lookups to reach nested types: Order["customer"]["address"].
  • T[number] gives the element type of an array or tuple type.
  • Index with a union of keys to get a union of property types: T["a" | "b"], or all of them with T[keyof T].
  • Indexed access lets you name parts of a big type without copying them.