Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Indexed Access Types: Syntax, Lookup Types, and Arrays

T[K] lookups on objects, arrays, and tuples, the undefined that optional properties add, and recursive path types built on indexed access.

~5 min readTypeScript
#TypeScript#Generics#Type Queries
3D illustration of bracket-indexed selectors plucking property type cubes from a nested object matrix

An indexed access type reads a property type out of another type: User["email"] is the type of the email property, and Group["members"][number] is the type of an element in that array. The syntax is the type-level twin of a property read, and it is the only way to express "the type of whatever lives under this key" without restating the shape — which is what makes generic helpers keyed by a property name stay in sync with the object they read.

Quick Summary

  • T[K] requires K to be assignable to keyof T; otherwise TS2536: Type 'K' cannot be used to index type 'T'.
  • Indexing with a union of keys produces a union of property types: T[keyof T] is every property type at once.
  • Arrays and tuples are indexed by number: T[number] is the element type, T[0] is the first tuple member, and T["length"] is the tuple's literal length.
  • On an object with an index signature, T[string] is the signature's value type, not a union of the declared keys.
  • Optional properties contribute undefined to the result under strictNullChecks, so T[K] of an optional key is not the same as the declared type.
  • T[never] is never, and T[any] is any; both appear in real code through computed generic keys.
  • typeof value gets a type from a runtime value, and (typeof arr)[number] is the standard way to type an array's elements from the array itself.
  • Indexed access composes: Pick<T, K>, Record<K, T[K]>, and recursive path helpers are all built on it.

Basic syntax and type signatures

typescript
interface User { id: string; name: string; age: number; tags?: readonly string[]; address: { street: string; city: string; zip: string }; } type Id = User["id"]; // string type NameOrAge = User["name" | "age"]; // string | number type Anything = User[keyof User]; // string | number | readonly string[] | undefined | {...} type Tags = User["tags"]; // readonly string[] | undefined type Street = User["address"]["street"]; // string type Elements = User["tags"][number]; // string type Tuple = ["a", "b"]; type First = Tuple[0]; // "a" type Len = Tuple["length"]; // 2 const roles = ["admin", "editor", "viewer"] as const; type Role = (typeof roles)[number]; // "admin" | "editor" | "viewer"

The generic form is where the operator earns its keep:

typescript
function get<T extends object, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } function pluck<T extends object, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]); } function set<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]): void { obj[key] = value; } declare const users: User[]; const ages: number[] = pluck(users, "age"); // pluck(users, "agee"); // error: "agee" is not keyof User // set(user, "age", "41"); // TS2345: string is not assignable to number

K extends keyof T is the constraint that makes T[K] legal; without it the lookup is TS2536. The return type T[K] is what keeps the value type tied to the chosen key — a function returning string | number for every key would type-check with the same body and reject nothing at the call site.

Comparison of type-level lookups

ExpressionResultLegal whenTypical use
T[K]property type of key KK extends keyof Tgeneric accessors
T[keyof T]union of all property typesalwaysexhaustively handling every value
T[number]element type of an array or tupleT is array-likederiving element types
T[0]first tuple elementT is a tupletuple helpers
T["length"]literal length for a tuple, number for arraysT is array-likefixed-arity checks
T[string]index signature value typeT has a string index signaturedictionaries
T[never]neveralwaysabsorbing keys in mapped types
T[any]anyalwaysrarely on purpose

The difference between T[keyof T] and T[string] matters: on { a: 1; b: 2 } the first is 1 | 2, the second is an error, because the type has no string index signature. On Record<string, number> the first is number (since keyof is string), and the second is also number, but T["a"] is number rather than an error, too — an index signature admits any key name.

Practical edge cases and deep dives

1. Optional properties, readonly, and the undefined that appears

typescript
interface Config { readonly host: string; port?: number; } type Host = Config["host"]; // string type Port = Config["port"]; // number | undefined function read<T extends object, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; // legal even when the key is optional } declare const cfg: Config; const p = read(cfg, "port"); // number | undefined

T[K] of an optional property includes undefined under strictNullChecks, because the property may be absent — the same reason obj.port is number | undefined. readonly does not change the looked-up type; it constrains assignment to the property, not the type of its value. The trap is a helper that promises T[K] and an implementation that assumes presence:

typescript
function required<T extends object, K extends keyof T>(obj: T, key: K): T[K] { const value = obj[key]; if (value === undefined) throw new Error(`missing ${String(key)}`); return value; // still T[K], which may include undefined }

The return type must be narrowed explicitly to make the guarantee visible, for example Exclude<T[K], undefined> with a cast at the return, because the compiler does not infer non-undefined from a runtime check that it cannot see through a generic parameter.

2. Arrays, tuples, and typeof as the source of truth

typescript
const ROUTES = [ { path: "/", title: "Home" }, { path: "/blog", title: "Blog" }, ] as const; type Route = (typeof ROUTES)[number]; // union of the two object literals type RoutePath = Route["path"]; // "/" | "/blog" type RouteTitle = (typeof ROUTES)[number]["title"]; // "Home" | "Blog" const PATHS = ROUTES.map((r) => r.path); // ("/" | "/blog")[] type AlsoPath = (typeof PATHS)[number]; // "/" | "/blog" because the array kept the literal

Reading types off a value removes the duplication that otherwise drifts: the array is the data, and every type derived from it moves when the data does. The single most useful idiom in this family is (typeof arr)[number], useful both for a readonly tuple of strings and for a plain array of objects, as long as the array is declared as const or the objects keep their literal types. user["tags"][number] on the earlier interface returns string even though the property is readonly string[]; the readonly modifier applies to the array, not to indexing it.

For tuples, T[0] and T["length"] expose structure:

typescript
type Pair = [string, number]; type Head<T extends readonly unknown[]> = T extends readonly [infer H, ...unknown[]] ? H : never; type HeadOfPair = Head<Pair>; // string type Check = Pair["length"] extends 2 ? true : false; // true

3. Recursive path lookups

typescript
type Primitive = string | number | boolean | bigint | symbol | null | undefined; type Paths<T, D extends number = 4> = [D] extends [never] ? never : T extends Primitive | readonly unknown[] ? never : { [K in keyof T & string]: | K | (T[K] extends Primitive ? never : `${K}.${Paths<T[K], Prev[D]>}`); }[keyof T & string]; type Prev = [never, 0, 1, 2, 3, 4]; type At<T, P extends string> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? At<T[Head], Rest> : never : P extends keyof T ? T[P] : never; interface Order { id: string; customer: { name: string; address: { city: string } }; } type OrderPath = Paths<Order>; // "id" | "customer" | "customer.name" | "customer.address" | "customer.address.city" type CityType = At<Order, "customer.address.city">; // string function lookup<T, P extends Paths<T>>(obj: T, path: P): At<T, P> { return path.split(".").reduce<any>((acc, key) => acc[key], obj) as At<T, P>; } declare const order: Order; const city = lookup(order, "customer.address.city"); // string

Two details make this safe enough to ship: a depth limit (D) that stops the compiler from expanding forever on recursive types, and a terminal never for primitives and arrays so paths do not descend into string's methods. The as At<T, P> inside lookup is unavoidable — the compiler cannot verify a reduce over a string split — which is the honest cost of path typing: the call site is checked, the implementation is not.

4. Deriving payload types from an event map

typescript
interface EventMap { "user:login": { userId: string; at: Date }; "user:logout": { userId: string }; "cart:add": { sku: string; qty: number }; } type Handler<K extends keyof EventMap> = (payload: EventMap[K]) => void; const handlers: { [K in keyof EventMap]: Handler<K> } = { "user:login": ({ userId }) => {}, "user:logout": ({ userId }) => {}, "cart:add": ({ sku, qty }) => {}, }; function emit<K extends keyof EventMap>(type: K, payload: EventMap[K]): void { handlers[type](payload); } emit("cart:add", { sku: "A-1", qty: 2 }); // emit("cart:add", { sku: "A-1" }); // error: qty is missing

EventMap[K] inside Handler<K> is what correlates the payload with the event name; the mapped handlers object then requires one handler per event with exactly the right parameter type, and emit can only be called with a matching pair. This is the pattern behind typed event emitters, message buses, and tRPC-style routers, and it relies on indexed access for every step.

5. Index signatures and the keys they admit

typescript
type Dict = { [key: string]: number }; type Value = Dict[string]; // number type Key = keyof Dict; // string | number type Flags = { [K in "a" | "b" | "c"]: boolean }; type FlagValue = Flags[keyof Flags]; // boolean // A type with both known and index-signature keys. interface Env { NODE_ENV: "development" | "production"; [key: string]: string | undefined; } type EnvValue = Env[string]; // string | undefined type NodeEnv = Env["NODE_ENV"]; // "development" | "production"

keyof of a string index signature is string | number, because JavaScript coerces numeric keys to strings, so a K extends keyof Dict helper accepts both. A declared property that is not assignable to the index signature is an error (TS2411), which is why the Env example needs | undefined on the signature: NODE_ENV's narrower type must fit inside what the signature promises. Reading a known key from such a type returns the declared type, not the signature's, because the property declaration takes precedence.

Common mistakes and compiler errors

Error or symptomCauseFix
TS2536: Type 'K' cannot be used to index type 'T'K not constrained to keyof TK extends keyof T, or cast through keyof
TS2339: Property 'x' does not exist on type 'T'literal key not present in the typecheck spelling, or index with a validated key
TS2537: Type 'X' has no matching index signature for type 'string'indexing an object type with stringadd an index signature or use keyof T
Result includes undefined unexpectedlythe property is optionalhandle it, or Exclude<T[K], undefined>
T[K] is anyK is any, or T is anyconstrain the key
Recursive path type hits TS2589: Type instantiation is excessively deepunbounded recursion over recursive typesadd a depth counter
(typeof arr)[number] is too widethe array was not as constadd as const, or type the literal elements
Tuple indexed with a variable gives a unionT[number] rather than T[0]use the literal index for a fixed position
Mapped type over keyof T loses keysthe source used Record<string, ...>keep the concrete object type and index it

The reliable habit is to derive rather than restate. Every time a property type is written twice — once in the interface and once in a parameter or return type — the two copies can diverge, and the compiler will keep saying yes to the older one. T[K], T[keyof T], and (typeof value)[number] are the three lookups that cover most of that work, and the recursive path helper covers the rest at the cost of a depth limit and one cast at the implementation boundary.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.