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
tsTry
interfaceCar {make : stringmodel : stringyear : numbercolor : {red : stringgreen : stringblue : string}}letcarColor :Car ["color"]
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:
tsTry
letProperty 'not-something-on-car' does not exist on type 'Car'.2339Property 'not-something-on-car' does not exist on type 'Car'.carColor :Car ["not-something-on-car" ]
You can also reach deeper into the object through multiple “accesses”
tsTry
letcarColorRedComponent :Car ["color"]["red"]
…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
tsTry
letcarProperty :Car ["color" | "year"]