TypeScript Course
TypeScript
/
Advanced

Indexed Access Types

Definition

A mechanism to look up a specific property on another type using bracket notation `Type['property']`, similar to accessing an object property in JavaScript.

Explain Like I'm New

If you have a massive API Response interface, and you only want to write a function that handles the 'Address' part of that response, you don't need to write a whole new Address interface. You just tell TS: 'Go into the API Response interface, look at the Address property, and give me whatever type is sitting there.'

Real World Example

Extracting the type of an array element: `type User = typeof usersArray[number];`

Common Use Cases

  • •Extracting nested types from 3rd-party libraries
  • •Keeping types DRY

Interactive Example

interface ApiResponse {
  user: {
    id: number;
    name: string;
    address: {
      street: string;
      zipCode: string;
    };
  };
  status: string;
}

// Look ma, no new interfaces! We just drill into the existing one.
type AddressType = ApiResponse["user"]["address"];

/* Evaluates to:
  {
    street: string;
    zipCode: string;
  }
*/

function validateZipCode(address: AddressType) {
  console.log(address.zipCode);
}

// Array extraction trick:
const roles = ["admin", "editor", "guest"] as const;
type RoleType = typeof roles[number]; // Evaluates to: "admin" | "editor" | "guest"

Interview Questions

basic

  • What is the syntax to access a type?

intermediate

  • How do you access the type of an array element?

advanced

  • Can you pass a union of strings into the index to get a union of types back?

Flash Cards

Question

How do you access an array element type?

Click to reveal answer
Answer

You index the array type with the keyword `number`. If `type List = string[]`, then `type Element = List[number]` evaluates to `string`.

Question

Can you pass a union into the index?

Click to reveal answer
Answer

Yes! If you do `Person['name' | 'age']`, TS goes into the Person interface, grabs the type for 'name', grabs the type for 'age', and returns them as a union (e.g., `string | number`).