Capítulo 8 de 36

Chapter 8: Indexed Access Types

Core Idea

Type['a'] pulls the type of a single property out of another type — the indexing key is itself a type, so it composes with unions, keyof, and typeof to slice out exactly the sub-type you need instead of redeclaring it.

Key Concepts

  • Basic form: type Age = Person["age"] extracts the type of the age property from Person.
  • The index can be a union: Person["age" | "name"] yields a union of both property types; Person[keyof Person] yields a union of every property's type.
  • Indexing a nonexistent property is a compile error — same safety as keyof, keeps the extraction in sync with the source type.
  • Indexing with number pulls an array/tuple's element type. Combined with typeof on an array literal, typeof MyArray[number] gives you the element type without writing it out by hand — and you can chain further: typeof MyArray[number]["age"].
  • Only types can index, not runtime const variables: const key = "age"; type Age = Person[key] is an error because key is a value, not a type. Use a type key = "age" alias instead if you want a named, reusable index.

Code Examples

const users = [{ name: "Alice", age: 15 }, { name: "Bob", age: 23 }];
type User = typeof users[number];       // { name: string; age: number }
type Age = typeof users[number]["age"]; // number
  • What it demonstrates: deriving an element type directly from an array literal via typeof + numeric indexed access, so the type always tracks the actual data shape.

Key Takeaways

  1. Prefer Type["prop"] (or Type[keyof Type]) over redeclaring a property's type elsewhere — it stays correct automatically when Type changes.
  2. typeof arrayLiteral[number] is the standard idiom for "the element type of this array, without a separate interface."
  3. Indexing requires a type, not a value — wrap a literal in type key = "age" if you want to name and reuse the index.

Connects To

  • Keyof/Typeof Operators: indexed access composes directly with both.
  • Mapped Types: often used together to remap a type while extracting per-property sub-types.
  • Conditional Types: the next building block for more advanced type-level logic.