Learn TypeScript w/ Mike North

Indexed Access Types

June 10, 2021

Indexed Access types provide a mechanism for retrieving part(s) of an array or object type via indices. We’ll look at how this kind of type works, and a couple of practical examples of where you might use them.

At the simplest level, these kinds of types are all about accessing some part of another type, via an index

ts
interface Car {
make: string
model: string
year: number
color: {
red: string
green: string
blue: string
}
}
 
let carColor: Car["color"]
let carColor: { red: string; green: string; blue: string; }
Try

In this situation 'color' is the “index”.

The index you use must be a valid “key” you could use on a value of type Car. Below you can see what happens if you try to break this rule:

ts
let carColor: Car["not-something-on-car"]
Property 'not-something-on-car' does not exist on type 'Car'.2339Property 'not-something-on-car' does not exist on type 'Car'.
Try

You can also reach deeper into the object through multiple “accesses”

ts
let carColorRedComponent: Car["color"]["red"]
let carColorRedComponent: string
Try

…and you can pass or “project” a union type (|) through Car as an index, as long as all parts of the union type are each a valid index

ts
let carProperty: Car["color" | "year"]
let carProperty: number | { red: string; green: string; blue: string; }
Try


© 2022 All Rights Reserved