Syncing account progress…

Back

Intermediate · 14 min

Indexed access types

Reuse property and array-element types instead of duplicating their definitions.

Read a type from another type

An indexed access type extracts a property type with square brackets. This happens in the type system, not at runtime. If the original property type changes, the derived type changes with it.

type Session = { topic: string; minutes: number };
type Duration = Session["minutes"];
const duration: Duration = 20;
console.log(duration + 5);

Output

25

Extract an array element type

Use an array type indexed by number to describe its elements. This does not prove a runtime array position exists. With noUncheckedIndexedAccess, an actual indexed read may still be undefined and must be checked.

type Plan = { sessions: { topic: string; minutes: number }[] };
type Session = Plan["sessions"][number];
const session: Session = { topic: "Travel", minutes: 15 };
console.log(session.topic);

Output

Travel

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Fix the task without using "any" or a type assertion, then check both practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Reuse the duration type

Use the number 25 for "duration" while keeping its indexed access type. Display the duration.

Show solution
type Session = { topic: string; minutes: number };
const duration: Session["minutes"] = 25;
console.log(duration);

The indexed access type reuses the numeric contract from Session. The value now matches that contract without a cast or duplicated type annotation.

Practice