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.

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]requiresKto be assignable tokeyof T; otherwiseTS2536: 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, andT["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
undefinedto the result understrictNullChecks, soT[K]of an optional key is not the same as the declared type. T[never]isnever, andT[any]isany; both appear in real code through computed generic keys.typeof valuegets 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
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:
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 numberK 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
| Expression | Result | Legal when | Typical use |
|---|---|---|---|
T[K] | property type of key K | K extends keyof T | generic accessors |
T[keyof T] | union of all property types | always | exhaustively handling every value |
T[number] | element type of an array or tuple | T is array-like | deriving element types |
T[0] | first tuple element | T is a tuple | tuple helpers |
T["length"] | literal length for a tuple, number for arrays | T is array-like | fixed-arity checks |
T[string] | index signature value type | T has a string index signature | dictionaries |
T[never] | never | always | absorbing keys in mapped types |
T[any] | any | always | rarely 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
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 | undefinedT[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:
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
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 literalReading 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:
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; // true3. Recursive path lookups
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"); // stringTwo 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
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 missingEventMap[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
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 symptom | Cause | Fix |
|---|---|---|
TS2536: Type 'K' cannot be used to index type 'T' | K not constrained to keyof T | K extends keyof T, or cast through keyof |
TS2339: Property 'x' does not exist on type 'T' | literal key not present in the type | check spelling, or index with a validated key |
TS2537: Type 'X' has no matching index signature for type 'string' | indexing an object type with string | add an index signature or use keyof T |
Result includes undefined unexpectedly | the property is optional | handle it, or Exclude<T[K], undefined> |
T[K] is any | K is any, or T is any | constrain the key |
Recursive path type hits TS2589: Type instantiation is excessively deep | unbounded recursion over recursive types | add a depth counter |
(typeof arr)[number] is too wide | the array was not as const | add as const, or type the literal elements |
| Tuple indexed with a variable gives a union | T[number] rather than T[0] | use the literal index for a fixed position |
Mapped type over keyof T loses keys | the 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 toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.