Lookup Types

A lookup type, also referred to as indexed access type, is a way to retrieve the type of a property of an object by its name or key. This is useful when you want to write code that works with dynamic property names, where the name of the property is not known until runtime.

The syntax for a lookup type is as follows: Type[Key], where Type is the type of the object and Key is the name of the property being looked up.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type Person = {
address: {
city: string;
country: string;
}
name: {
firstName: string;
lastName: string;
}
}

// Lookup types "Address" and "Name"
type Address = Person['address'];

type Name = Person['name'];

// Lookup types in action!
function getProperty(property: keyof Person, person: Person): Address | Name {
return person[property];
}