Sub topic 5
Looking up property types with T[K]
An indexed access type reads the type of a property from another type. This chapter assumes you know interfaces, type aliases, union types, and basic generics. It also assumes you have read the earlier chapters on keyof and typeof. You will use keyof and typeof here, but you don't need the later chapters on mapped types or ReturnType.
The working model
Indexed access types use the bracket syntax you know from JavaScript, but in a type position. If T is a type and K is a key of T, then T[K] is the type of that property.
interface User {
id: number;
name: string;
email?: string;
}
type IdType = User["id"]; // number
type NameType = User["name"]; // stringThink of it as a lookup table. User maps key names to types, and User["id"] asks for the entry under "id". The result is a type. No code runs, and nothing exists at runtime.
The index must be a type, usually a string literal type such as "id". It can also be a union of literals, keyof T, a type parameter constrained to keyof T, or number for arrays.
Single keys, unions, and keyof
The index can be a union of keys. TypeScript looks up each member and unions the results.
interface User {
id: number;
name: string;
email?: string;
}
type EmailType = User["email"]; // string | undefined
type NameOrId = User["name" | "id"]; // string | number
type AnyValue = User[keyof User]; // string | number | undefinedUser[keyof User] gives the union of every property type. You will often see it wrapped in a helper:
type ValueOf<T> = T[keyof T];
const Status = {
Active: "active",
Archived: "archived",
} as const;
type StatusValue = ValueOf<typeof Status>; // "active" | "archived"This combines three tools from this tutorial. typeof Status turns the runtime object into a type. keyof lists its keys, and the index looks up every value type. The as const keeps the values as literals instead of widening them to string. A later chapter covers as const in detail.
Optional properties add undefined
email?: string means the property may be missing, so reading it can give undefined. The lookup reflects that, which is why User["email"] is string | undefined. This holds when strictNullChecks is on, which strict enables.
If you want the type without undefined, wrap the lookup in NonNullable:
interface User {
id: number;
name: string;
email?: string;
}
type DefiniteEmail = NonNullable<User["email"]>; // string
function sendTo(address: DefiniteEmail): void {
console.log(`Sending to ${address}`);
}
sendTo("[email protected]");NonNullable also strips an explicit null. If you only want to remove undefined, use Exclude<User["email"], undefined>.
Chaining lookups into nested types
An indexed access type is itself a type, so you can index it again. This is the main tool for reaching into nested object types without naming each level.
interface Order {
id: string;
customer: {
name: string;
address: {
city: string;
zip: string;
};
};
items: { sku: string; qty: number }[];
}
type Customer = Order["customer"]; // { name: string; address: { city: string; zip: string } }
type City = Order["customer"]["address"]["city"]; // string
type Item = Order["items"][number]; // { sku: string; qty: number }
type Sku = Order["items"][number]["sku"]; // stringOrder["items"] is an array type. Indexing an array type with number gives its element type. That is the same mechanism a later chapter uses for as const arrays, so treat [number] here as a preview.
Why look up instead of declaring a new type
Suppose a function accepts the customer's address. You could write a separate Address interface and keep it in sync with Order by hand. Or you can derive it:
interface Order {
id: string;
customer: {
name: string;
address: { city: string; zip: string };
};
}
type Address = Order["customer"]["address"];
function formatAddress(address: Address): string {
return `${address.city} ${address.zip}`;
}
console.log(formatAddress({ city: "Leeds", zip: "LS1 4AP" }));If Order changes, Address follows. This is most useful when Order comes from a library or generated code that you can't edit.
Indexing tuples and methods
Tuples have numeric-literal keys, so you can look up a position:
type Pair = [string, number];
type First = Pair[0]; // string
type Second = Pair[1]; // number
type Either = Pair[number]; // string | number
// type Third = Pair[2]; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'.Methods are properties whose type is a function type, so they can be looked up too:
interface Greeter {
greet(name: string): string;
}
type GreetFn = Greeter["greet"]; // (name: string) => stringThe readonly modifier does not change the result. { readonly id: number }["id"] is number.
Using T[K] in generics
Indexed access types matter most in generic code. When K extends keyof T, the type T[K] tracks which property the caller picked.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProperty(user, "name"); // type: string
const id = getProperty(user, "id"); // type: number
// getProperty(user, "age"); // Error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name"'.Without T[K], the return type would have to be T[keyof T], the union of all property types. Callers would then need to narrow it. With K as a type parameter, TypeScript infers K as the literal "name" or "id" from the call, and T[K] resolves to exactly that property's type.
You can also name the lookup as a reusable alias:
type PropType<T, K extends keyof T> = T[K];
interface Product {
sku: string;
price: number;
}
type Price = PropType<Product, "price">; // numberThe extends keyof T constraint is required. Without it, TypeScript can't prove that K is a valid index of T and reports an error.
Setting a property safely
A setter shows why the lookup is useful on the input side too:
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const point = { x: 1, y: 2, label: "origin" };
setProperty(point, "x", 10); // OK
setProperty(point, "label", "start"); // OK
// setProperty(point, "x", "ten"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.The value parameter is typed T[K], so passing a string for "x" is rejected. A plain value: T[keyof T] would accept any of the property types for any key.
Common errors
Most mistakes with indexed access types come from mixing up values and types.
| Mistake | What happens | Fix | Column |
|---|---|---|---|
| `User.id` in a type position | Error: dot notation does not work in types | Write `User["id"]` | |
| `User[key]` where `key` is a variable | Error: `'key' refers to a value, but is being used as a type here` | Write `User[typeof key]` | |
| `User["age"]` for a missing key | Error: `Property 'age' does not exist on type 'User'` | Check the key against `keyof User` | |
| Ignoring ` | undefined` on optional properties | Later code fails to compile or crashes | Handle it, or use `NonNullable` |
| `string` as the index on a type with fixed keys | Error: no index signature for `string` | Use `keyof T` or a literal union |
The second row is the most common one. A runtime variable can't be an index type directly:
interface User {
id: number;
name: string;
}
const field = "name";
// type Bad = User[field]; // Error: 'field' refers to a value, but is being used as a type here.
type Good = User[typeof field]; // stringThis works because const field = "name" has the literal type "name", not string. If you had written let field = "name", its type would widen to string. Then User[typeof field] would fail, since string is not a key of User.
Lookups on index signatures and unions
Two edge cases come up often enough to know now. Later chapters cover them in full.
With an index signature, the type of any string key is the signature's value type:
type Dict = { [key: string]: boolean };
type Flag = Dict["anything"]; // boolean
type Flag2 = Dict[string]; // booleanWith a union as the object type, the key must exist in every member. The result is the union of the matching property types:
type A = { kind: "a"; value: number };
type B = { kind: "b"; value: string };
type Kind = (A | B)["kind"]; // "a" | "b"
type Value = (A | B)["value"]; // number | stringHere value exists in both members, so the lookup works. If B had no value property, (A | B)["value"] would be an error, because TypeScript can't read a property that one member lacks.
Summary of forms
| Form | Meaning | Example result | Column | Column |
|---|---|---|---|---|
| `T["k"]` | Type of one property | `User["id"]` is `number` | ||
| `T["a" \ | "b"]` | Union of several property types | `string \ | number` |
| `T[keyof T]` | Union of all property types | `string \ | number \ | undefined` |
| `T[K]` with `K extends keyof T` | Property type chosen by the caller | `getProperty` return type | ||
| `T[number]` | Element type of an array or tuple | `Order["items"][number]` | ||
| `T[A][B]` | Chained lookup into nested types | `Order["customer"]["address"]` |
Exercise
Given interface Account { id: string; owner: { name: string; age?: number }; tags: string[] }, write type aliases for (1) the type of age, (2) the type of age without undefined, and (3) a single tag.
Show answer
type Age = Account["owner"]["age"]; // number | undefined
type DefiniteAge = NonNullable<Account["owner"]["age"]>; // number
type Tag = Account["tags"][number]; // string
The optional age adds undefined to the lookup, NonNullable removes it, and indexing the array type with number gives the element type.
Exercise
Why does this fail, and how do you fix it? const key = "id"; type T = User[key]; where User has an id: number property.
Show answer
key is a value, and an index in a type position must be a type. TypeScript reports that 'key' refers to a value, but is being used as a type here. Use typeof key to read the value's type: type T = User[typeof key];, which is number. This works because const key = "id" has the literal type "id".