Indexed access types
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.
Looking up a property type
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"]; // stringThe 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:
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:
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 | numberYou’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:
type IdOrName = User["id" | "name"]; // number | string
type AnyValue = User[keyof User]; // every property type, as a unionT[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:
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:
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:
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:
type Profile = { bio?: string };
type Bio = Profile["bio"]; // string | undefinedTo 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.
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.
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" },
};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
type Customer = OrderResponse["customer"];
type Address = OrderResponse["customer"]["address"];
type LineItem = OrderResponse["items"][number];
type Status = OrderResponse["status"];
type Currency = OrderResponse["total"]["currency"];
// shippingLabel, lineTotal, isOpen
function shippingLabel(customer: Customer): string {
const { city, country }: Address = customer.address;
return `${customer.name}, ${city} ${country}`;
}
function lineTotal(item: LineItem): number {
return item.quantity * item.unitPrice;
}
function isOpen(status: Status): boolean {
return status === "pending" || status === "paid";
}
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" },
};
const currency: Currency = order.total.currency;
console.log(shippingLabel(order.customer)); // Asha Rao, Pune IN
console.log(order.items.reduce((sum, item) => sum + lineTotal(item), 0), currency); // 63.98 INR
console.log(isOpen(order.status)); // true
// @ts-expect-error -- "lost" is not a Status
isOpen("lost");Summary
T["key"]is the type of propertykeyon type T — likeobj["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 withT[keyof T]. - Indexed access lets you name parts of a big type without copying them.