TypeScript Indexed Access Types
Indexed access types let you look up the type of a specific property within another type, using syntax similar to accessing a property at runtime, but at the type level.
Writing `User["name"]` as a type gets you the exact type of the name property from the User type, which is useful for keeping related types in sync without duplication.
type Age = User["age"];Basic indexed access
For `interface User { name: string; age: number }`, the type `User["age"]` equals `number`, the type of that specific property.
Combining with keyof
You can combine indexed access with keyof to get the type of any property value, like `User[keyof User]`, which produces a union of all property value types.
interface User {
name: string;
age: number;
}
type Age = User["age"];
const myAge: Age = 25;
console.log(myAge);25Age is derived directly from the age property of User, so it stays in sync if User changes.
interface Response {
data: { id: number; title: string };
}
type DataType = Response["data"];
const item: DataType = { id: 1, title: "Post" };
console.log(item.title);PostDataType is extracted from the nested data property of Response, avoiding a duplicate type definition.
Key points
- Indexed access types read a property's type from another type.
- The syntax mirrors runtime property access, like Type["propertyName"].
- They keep derived types automatically in sync with their source.
- Combined with keyof, they can extract a union of all property value types.
