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

Loading Code Playground...

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`).