TypeScript Reference ยท Type Operators
TypeScript indexed access types
Reference for indexed access types in TypeScript: T[K], unions of keys, number indexes on arrays and tuples, nested lookups and the errors you can hit.
An indexed access type looks up the type of a property on another type, using the same square-bracket syntax you use on values. If User has a property email: string, then User["email"] is string. It lets you refer to part of a type without repeating it.
The index can be a literal key, a union of keys, keyof T, or number for arrays and tuples. When it is a union, the result is the union of the matching property types.
interface User { id: number; name: string; email: string } type Email = User["email"]; // string type IdOrName = User["id" | "name"]; // string | number
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Result = ObjectType[IndexType];
| Name | Description |
|---|---|
ObjectType |
Any type with properties: an object type, an array, a tuple, an intersection. |
IndexType |
A type assignable to keyof ObjectType: a string literal, a number literal, a union of those, keyof ObjectType, or number/string when an index signature exists. |
Errors and edge cases:
- An unknown key is an error:
User["phone"]gives "Property 'phone' does not exist on type 'User'". - A variable cannot be the index.
User[key]wherekeyis a value is invalid in type position; useUser[typeof key]. - On a union, every member must have the key, or the lookup fails.
- With
exactOptionalPropertyTypesoff, an optional propertya?: stringyieldsstring | undefined.
Usage notes
- Unions of keys distribute:
T["a" | "b"]isT["a"] | T["b"]. T[number]is the element type of any array or tuple type, and also of areadonlyarray.- Tuples accept numeric literals (
Pair[0]) and"length", which is a literal number type. - Nested lookups chain:
Order["customer"]["name"]. - Generic functions use
T[K]withK extends keyof Tto return a precise type per call, as ingetPropabove. - Mapped types use it to read the original property type while building a new one; see mapped types.
- Limitations: it reads declared property types; it cannot look up methods that live only on a prototype chain you did not declare.
- It is erased at compile time and has no runtime cost.