TypeScript Indexed Access Types
Indexed Access Types (also called "Lookup Types") allow you to retrieve the type of a specific property from another type. This is similar to accessing a property on an object in JavaScript using bracket notation (obj['key']), but for types.
1. Basic Syntax
You use square brackets [] with the key name (as a string literal type) to access the property type.
type Person = {
age: number;
name: string;
alive: boolean;
};
// Look up the type of 'age'
type Age = Person["age"];
// type Age = number
2. Accessing Multiple Properties (Unions)
You can pass a union of keys to get a union of their types.
type Person = {
age: number;
name: string;
alive: boolean;
};
type I1 = Person["age" | "name"];
// type I1 = number | string
type I2 = Person[keyof Person];
// type I2 = number | string | boolean
3. Accessing Array Element Types
A very common use case is extracting the type of elements inside an array or tuple. You can use number as the index to get the type of array elements.
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
{ name: "Eve", age: 38 },
];
// 1. Get the type of the array itself
type PersonArray = typeof MyArray;
// 2. Get the type of a single item inside the array
type Person = PersonArray[number];
// type Person = { name: string; age: number; }
// 3. Get the type of a specific property of items in the array
type Age = PersonArray[number]["age"];
// type Age = number
4. Dynamic Access with Generics
You can use Indexed Access Types inside generics to ensure type safety when accessing properties dynamically. This pattern captures the return type based on the key passed in.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const car = { make: "Toyota", year: 2020 };
const make = getProperty(car, "make");
// TypeScript knows 'make' is a string
const year = getProperty(car, "year");
// TypeScript knows 'year' is a number