We can use an indexed access type to look up a specific property on another type. Let’s take a look at the example:
type User = {
id: number;
username: string;
email: string;
address: {
city: string;
state: string;
country: string;
postalCode: number;
};
addons: { name: string, id: number }[];
};
type id = User["id"]; // number
type Session = User["address"];
// {
// city: string;
// state: string;
// country: string;
// postalCode: string;
// }
type Street = User["address"]["state"]; // string
type Addons = User["addons"][number]; // { name: string; id: number; }
Here we create a new type such as
or we can use it directly in a function like this:
function printAddress(address: User["address"]): void {
console.log(`
city: ${address.city},
state: ${address.state},
country: ${address.country},
postalCode: ${address.postalCode}
`);
}