[Typescript] Index access types
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.
interface Car {
make: string
model: string
year: number
color: {
red: string
green: string
blue: string
}
}
We can get color
type:
let carColor: Car["color"]
/*
let carColor: {
red: string;
green: string;
blue: string;
}
*/
We can get nested prop type:
let carColorRedComponent: Car["color"]["red"] // string
Index access type has safe guard:
let carColor: Car["not-something-on-car"] // ERROR: Property 'not-something-on-car' does not exist on type 'Car'.
We can get Intersection types on index access types:
let carPropertyWeInterest: Car["color" | "year", "model"]
/*
string | number | {
red: string;
green: string;
blue: string;
}
*/