Skip to content
jshacks.dev
TypeScript

Indexed Access Types

Look up the type of a property with T[K], reach into nested objects and arrays, and build unions from tuples and keys. Learn the syntax and the errors.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, npm, JavaScript and Node.js logos.

In JavaScript you read a property with order.total, or with order["total"] when the name is in a variable. TypeScript has the same idea one level up: an indexed access type, written Order["total"], looks up the type of a property on a type. It lets you reuse a type that already exists instead of copying it, so that a function parameter, a response field and a database column stay in step with one definition. This post covers the lookup syntax, nested lookups, array and tuple indexing with number, lookups with a union of keys, the errors you get for names that do not exist, and the generic form T[K] that underlies many utility types. It uses TypeScript 6.x, and the reference is the handbook page on indexed access types.

Looking up a property type

The square-bracket form takes a type on the left and a literal key type inside the brackets. The result is the type of that property.

order.tsTypeScript
export interface Order {
  id: string;
  total: number;
  customer: { name: string; vip: boolean };
  tags: string[];
}
access.tsTypeScript
import type { Order } from "./order.js";

type Total = Order["total"];
type CustomerName = Order["customer"]["name"];
type Tag = Order["tags"][number];

const total: Total = 42;
const name: CustomerName = "Ada";
const tag: Tag = "gift";

console.log(total, name, tag);
Text
42 Ada gift

Total is number, CustomerName is string, and Tag is string. Each lookup can be chained, so Order["customer"]["name"] descends into the nested object type. The last one indexes the tags array type with number, which means "the type of any element", and gives string. Nothing in the example has a separate declaration of these types, and if customer.name later becomes a union, CustomerName follows.

The compiler checks the lookups like it checks anything else.

access-bad.tsTypeScript
import type { Order } from "./order.js";

const wrong: Order["total"] = "42";
Text
access-bad.ts(3,7): error TS2322: Type 'string' is not assignable to type 'number'.

A key that does not exist

Looking up a name the type does not have is an error at the lookup, not at a later use.

missing-key.tsTypeScript
import type { Order } from "./order.js";

type Phone = Order["phone"];
Text
missing-key.ts(3,20): error TS2339: Property 'phone' does not exist on type 'Order'.

This makes indexed access types a form of refactoring support. If someone renames total to amount in Order, every Order["total"] in the program fails to compile, and the compiler lists them. Copying the type as a bare number in each place gives no such warning.

The brackets also take a type, not a value. A variable holding the string "total" does not work as an index unless you name its type with typeof. And the dot form is not available for types at all.

dot.tsTypeScript
import type { Order } from "./order.js";

type T = Order.total;
Text
dot.ts(3,10): error TS2503: Cannot find namespace 'Order'.

Dots in a type position mean namespace members. A property lookup always uses brackets.

Several keys at once

The index can be a union of keys, and the result is the union of the property types. That is a quick way to say "any of these fields".

union-keys.tsTypeScript
import type { Order } from "./order.js";

type IdOrTotal = Order["id" | "total"];

const a: IdOrTotal = "A-100";
const b: IdOrTotal = 250;
const c: IdOrTotal = true;
Text
union-keys.ts(7,7): error TS2322: Type 'boolean' is not assignable to type 'string | number'.

Using keyof as the index gives every property, so Order[keyof Order] is the union of all the value types. Here that is string | number | { name: string; vip: boolean } | string[]. It is useful in generic code, for example to describe a function that accepts any value stored in an object. The keyof operator itself is covered in the previous post in this series.

Indexing arrays and tuples

An array type has a number index signature, so T[number] is the element type. This works on array types and on readonly arrays, and it is the standard way to turn a list into a union.

roles.tsTypeScript
const roles = ["admin", "editor", "viewer"] as const;

type Role = (typeof roles)[number];

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

console.log(isRole("editor"));
console.log(isRole("owner"));
Text
true
false

With as const, the array is a readonly tuple of literals, so Role is "admin" | "editor" | "viewer". The list exists once, at runtime, and the type is derived from it. The cast inside isRole is the usual small cost: includes on a tuple of literals accepts only those literals, so the argument is widened to readonly string[] for the check.

Tuples can also be indexed by position, with a literal number, and the compiler knows the length.

tuple.tsTypeScript
type Pair = [string, number];

type First = Pair[0];
type Second = Pair[1];
type Third = Pair[2];
Text
tuple.ts(5,19): error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'.

First is string and Second is number. The third lookup is rejected because the tuple has two elements. For an ordinary array, string[][2] is allowed and gives string, since arrays do not track their length.

Optional properties

A lookup on an optional property includes undefined, because the property may be missing.

profile.tsTypeScript
interface Profile {
  username: string;
  nickname?: string;
}

type Nick = Profile["nickname"];

const nick: Nick = 7;
Text
profile.ts(8,7): error TS2322: Type 'number' is not assignable to type 'string | undefined'.

If you want the type without undefined, wrap the lookup in NonNullable, as in NonNullable<Profile["nickname"]>. With exactOptionalPropertyTypes enabled, an optional property's type is described a little differently, and the setting is worth reading about before relying on this for optional fields.

Pulling a type out of a response

A common use is naming a piece of a large type that you do not own, such as a response shape, so that a helper can accept just that piece.

items.tsTypeScript
interface ListResponse {
  data: {
    items: Array<{ sku: string; price: number }>;
    nextCursor: string | null;
  };
}

type Item = ListResponse["data"]["items"][number];

function formatItem(item: Item): string {
  return `${item.sku} costs ${item.price.toFixed(2)}`;
}

console.log(formatItem({ sku: "KB-1", price: 49 }));
Text
KB-1 costs 49.00

If the API type changes the shape of an item, formatItem is checked against the new shape, and call sites that build items by hand fail to compile. A hand-copied { sku: string; price: number } in the helper would continue to compile and drift.

The generic form

Inside a generic function or type, the key is often a type parameter, constrained to the keys of the object type. The lookup T[K] then describes the result of reading that property.

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

const order = { id: "A-100", total: 250, tags: ["gift"] };

console.log(get(order, "total") + 1);
console.log(get(order, "tags").length);
Text
251
1

For the first call, T[K] is number, so addition type-checks. For the second, it is string[], and .length is available. The signature relates the result to both the object and the key, which is exactly what indexed access types are for.

Many of the standard utility types are built from the same parts. A mapped type that makes every property nullable reads each property type through T[K].

nullable.tsTypeScript
type Nullable<T> = { [K in keyof T]: T[K] | null };

type Draft = Nullable<{ title: string; words: number }>;

const draft: Draft = { title: "Indexed access", words: null };

console.log(draft);
Text
{ title: 'Indexed access', words: null }

K in keyof T walks the keys, and T[K] is the type of each one. This is the machinery behind Partial, Readonly and Pick, and understanding it makes those types readable.

What it does not do

An indexed access type describes types, not values, so it never reads anything at runtime. It is also only as precise as the type you give it. If a property is typed string, Order["id"] is string, even when every id in your data matches a pattern. And it describes declared members, not keys that happen to exist on a value at runtime.

The noUncheckedIndexedAccess compiler option affects expressions such as list[0], which become T | undefined, and it does not change the indexed access types you write in type positions. People mix these up because the syntax looks alike.

Testing

As with other type-level features, the check is the compiler. Keep a small file that assigns values to the derived types, and run it as part of the type check in continuous integration, so a renamed property fails the build rather than a user.

access.test.tsTypeScript
import type { Order } from "./order.js";

const id: Order["id"] = "A-100";
const customerVip: Order["customer"]["vip"] = true;

console.log(id, customerVip);
Text
A-100 true
Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.