Indexed access types let you get the type of a specific property from another type. This helps you reuse types easily without repeating them.
Indexed access types in Typescript
type NewType = ExistingType['propertyName'];You use square brackets with the property name as a string inside to get the type.
You can also use union of keys like ExistingType['prop1' | 'prop2'] to get combined types.
name property from Person, which is string.type Person = { name: string; age: number };
type NameType = Person['name'];age or name, so the type is number | string.type Person = { name: string; age: number };
type AgeOrName = Person['age' | 'name'];make property from the Car interface.interface Car {
make: string;
year: number;
}
type MakeType = Car['make'];This program shows how to use indexed access types to get property types from the User interface. We assign values matching those types and print them.
interface User {
id: number;
username: string;
isActive: boolean;
}
// Get the type of the 'username' property
let userName: User['username'];
userName = 'alice123';
// Get the type of 'id' or 'isActive'
let userInfo: User['id' | 'isActive'];
userInfo = 42; // valid
userInfo = true; // also valid
console.log(userName);
console.log(userInfo);Indexed access types help keep your types consistent and avoid mistakes.
If you use a property name that does not exist, TypeScript will show an error.
You can combine indexed access types with other TypeScript features for powerful type manipulation.
Indexed access types let you get the type of a property from another type.
Use square brackets with the property name to extract the type.
This helps reuse types and keep your code clean and safe.