Indexed access types

Intermediate · 21 min

Looking up a property's type with T[K]: nested lookups, unions of keys, T[keyof T], T[number] for arrays, and the typeof arr[number] pattern.

Before thisThe keyof and typeof type operatorsArrays and tuplesGeneric constraints

Dmytro Danylov · 21 min

Indexed access types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Dmytro DanylovReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An indexed access type `T["prop"]` looks up the type of one property, the way `obj["prop"]` looks up a value, so a nested piece of a large type can be named without copying it.
  • The index must itself be a type that is a valid key of `T`; dot syntax doesn't work in types, and indexing with an unknown key is an error rather than `undefined`.
  • Indexing with a union of keys gives the union of their property types, so `T[keyof T]` is the union of every property type in `T`.
  • `T[number]` gives the element type of an array, and of a tuple it gives the union of every element type; a numeric literal like `T[0]` picks one tuple position.
  • `(typeof ROLES)[number]` on an array declared `as const` turns a runtime list of strings into a union type, so the array is the single source of truth for both the values and the type.
  • In a generic function, a parameter `key: K` with `K extends keyof T` and a return type of `T[K]` ties the return type to the specific key the caller passed.

Naming a piece of someone else’s type

Large types often arrive from somewhere else: a generated API client, a library, a config schema. You need one nested piece of it, say the shape of user inside a response, for a function parameter. Copying the fields into a new interface works until the API changes and your copy doesn’t.

Indexed access types let you point at that piece instead. The syntax mirrors reading a property with brackets at runtime:

interface ApiResponse {
  status: number;
  data: {
    user: { id: string; name: string; tags: string[] };
    permissions: ("read" | "write" | "admin")[];
  };
}

type Status = ApiResponse["status"]; // number
type User = ApiResponse["data"]["user"]; // { id: string; name: string; tags: string[] }

function greet(user: User) {
  return `Hello, ${user.name}`;
}

Lookups chain, so ApiResponse["data"]["user"]["tags"] is string[]. If the server adds an email field to user, User gains it with no edit on your side.

The rules of the index

The thing inside the brackets is a type, not a value. Three consequences follow:

type ViaDot = ApiResponse.status; // Error: 'ApiResponse' is a type, not a namespace

const field = "status";
type ViaVariable = ApiResponse[field]; // Error: 'field' refers to a value
type ViaTypeof = ApiResponse[typeof field]; // number

type Missing = ApiResponse["headers"]; // Error: no property 'headers'

Dot syntax is reserved for namespaces, so types always use brackets. A variable needs typeof to become a type first. And unlike JavaScript, where a missing property gives undefined, a missing key here is a compile error. That error is the point: the lookup is checked.

Unions of keys, and T[keyof T]

The index can be a union, and the result is the union of the matching property types:

interface Settings {
  theme: "light" | "dark";
  fontSize: number;
  autosave: boolean;
}

type ThemeOrSize = Settings["theme" | "fontSize"]; // "light" | "dark" | number
type SettingValue = Settings[keyof Settings]; // "light" | "dark" | number | boolean

T[keyof T] feeds every key from the previous lesson’s keyof back in as the index, giving “any property value of T.” It’s the type-level version of Object.values.

Arrays and tuples: T[number]

Arrays have numeric keys, so you can index them with the type number. That gives the element type, which is the cleanest way to unwrap an array type you didn’t declare yourself:

type Permission = ApiResponse["data"]["permissions"][number]; // "read" | "write" | "admin"

type Entry = [label: string, count: number];
type Label = Entry[0]; // string
type AnyCell = Entry[number]; // string | number
type EntryLength = Entry["length"]; // 2

For a tuple, a numeric literal picks one position and number gives the union of all positions. Tuples even expose their fixed length as a literal type.

typeof arr[number] with as const

Combine T[number] with typeof and you get one of the most common patterns in TypeScript code: a runtime list that is also the source of a union type.

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

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

const LOOSE = ["viewer", "editor", "owner"];
type LooseRole = (typeof LOOSE)[number]; // string

The array gives you something to loop over in a dropdown or validate against at runtime, and Role comes from the same list, so they can’t disagree. The as const is essential. Without it, LOOSE is inferred as string[], and its element type is just string. With it, the array becomes a readonly tuple of exact literals.

The parentheses are optional, since typeof ROLES[number] parses the same way, but they make the order of operations obvious to readers. The object version is (typeof STATUS)[keyof typeof STATUS], which gives the union of an as const object’s values.

Indexed access in generics

The last piece fixes the loose return type from the keyof lesson. Give the key its own type parameter and return T[K]:

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

const account = { id: 7, owner: "Ada", active: true };
const id = getProp(account, "id"); // number
const owner = getProp(account, "owner"); // string
getProp(account, "email"); // Error: '"email"' is not one of the keys

TypeScript infers K as the literal key at each call, so the return type follows the key. A return type of T[keyof T] would have been number | string | boolean everywhere. This K extends keyof T and T[K] pairing shows up throughout library typings, and mapped types are built on it.

About the video

Dmytro Danylov’s video is a dedicated, chaptered walkthrough of indexed access types, which it also calls lookup types: T["prop"], indexing with unions of keys, T[keyof T], and combining lookups with keyof and generics. It was recorded in 2020, but this feature hasn’t changed since. It doesn’t put much weight on T[number] for arrays and tuples, so the last two sections above fill that gap. At twenty minutes it’s the longest video in this group; the Matt Pocock link below is a 79-second recap of the union-of-keys trick.

Check yourself

  1. 01Why write `ApiResponse["data"]["user"]` instead of declaring a separate `User` interface with the same fields?

    A separate interface is a copy that has to be kept in step with `ApiResponse` by hand. The indexed access type is a lookup, so when the response's `user` shape changes, every type derived from it changes too, and any code relying on the old shape fails to compile instead of silently drifting.

  2. 02Given `const key = "status";`, why does `ApiResponse[key]` fail, and what works instead?

    The index in an indexed access type must be a type, and `key` is a value. `ApiResponse[typeof key]` works, because `typeof key` is the literal type `"status"`. Writing `ApiResponse["status"]` directly also works.

  3. 03What is `[string, number, boolean][number]`, and how does it differ from `[string, number, boolean][1]`?

    Indexing a tuple with `number` asks for the type at any numeric position, which is the union `string | number | boolean`. Indexing with the literal `1` asks for one position, which is `number`.

  4. 04Why does `(typeof SIZES)[number]` give `"sm" | "md" | "lg"` only when `SIZES` is declared with `as const`?

    Without `as const`, TypeScript infers the array as `string[]`, because a mutable array could later hold any string, so its element type is just `string`. `as const` makes it a readonly tuple of the exact literals, and indexing that tuple with `number` gives the union of those literals.

  5. 05How does `function get<T, K extends keyof T>(obj: T, key: K): T[K]` improve on a return type of `T[keyof T]`?

    `T[keyof T]` is the union of every property type, whichever key is passed. With `K` as its own type parameter, TypeScript infers the literal key from each call, so `get(user, "id")` returns exactly the type of `id`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark