TypeScript ยท Chapter 35 of 44

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.

Syntax
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.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
}
type Age = User["age"];
const myAge: Age = 25;
console.log(myAge);
Output
25

Age is derived directly from the age property of User, so it stays in sync if User changes.

Example 2 (typescript)
interface Response {
  data: { id: number; title: string };
}
type DataType = Response["data"];
const item: DataType = { id: 1, title: "Post" };
console.log(item.title);
Output
Post

DataType 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.
๐Ÿ’ก Note: Indexed access types reduce duplication when a type's shape might evolve over time.

๐Ÿ“ Quick Quiz

1. What does `User["age"]` represent as a type?

2. What does User[keyof User] produce?

3. Why use indexed access types?