tezvyn:

Indexed Access Types: Look Up a Property's Type

AI-drafted, machine-checkedSource: typescriptlang.orgbeginner

Indexed access types let you look up a property's type on another type, like `Person['age']` yielding `number`. Use them to create new types from existing ones, like getting an array element's type with `MyArray[number]`.

WHY IT EXISTS To avoid manually redefining types that are already implicitly defined within other types. Indexed access types let you create new types from pieces of existing ones, promoting DRY (Don't Repeat Yourself) principles in your type system and ensuring consistency when an underlying type changes.

THE MENTAL MODEL Think of it as compile-time property access. Just as person.age gives you the value of the age property at runtime, Person['age'] gives you the type of the age property at compile time. It's a way to query your type system using familiar bracket notation.

HOW IT WORKS You use the syntax T[K], where T is a type and K is a type representing a key. K can be a string literal like 'age', a union of literals like 'name' | 'age', or another type operator like keyof Person. For arrays, using the number type as the index (MyArray[number]) extracts the type of the elements within the array. The TypeScript compiler will error if you try to index a property that doesn't exist on the type T.

WHEN TO USE IT Use indexed access types when you need to create a new type from a part of an existing one. This is common for three scenarios: first, grabbing the type of a single property from an object; second, extracting the element type from an array; and third, creating a union type from several properties of an object, for example Person['name' | 'alive'] which results in string | boolean.

WHEN NOT TO USE IT The main limitation is that you cannot use a runtime value, like a variable declared with const, as the index. The index key must be a type. For example, const key = 'age'; type Age = Person[key]; will fail because key is a value. You must use a type literal ('age') or a type alias (type AgeKey = 'age';).

ONE CANONICAL EXAMPLE Given an array of objects, you can derive both the object type and the type of its properties without defining them manually. Consider this array: const MyArray = [{ name: 'Alice', age: 15 }, { name: 'Bob', age: 23 }];. To get the type of an object in the array, you'd write type Person = typeof MyArray[number];. This infers the type { name: string; age: number; }. Then, to get just the age type, you can use that new type: type Age = Person['age'];, which results in number.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.