Indexed Access Types

T[K]: The Type of a Property

T["prop"] looks up the type of a property, just like reading a value. You can index with a union of keys, and T[number] gives the element type of an array.

Example

type Order = {
  id: string;
  customer: { name: string; phone: string };
  items: { sku: string; qty: number; price: number }[];
  status: "PLACED" | "SHIPPED" | "DELIVERED";
};

type Customer = Order["customer"];          // { name: string; phone: string }
type OrderItem = Order["items"][number];    // { sku; qty; price }
type Status = Order["status"];              // "PLACED" | "SHIPPED" | "DELIVERED"
type IdOrStatus = Order["id" | "status"];   // string

const item: OrderItem = { sku: "SKU-1", qty: 2, price: 250 };
const c: Customer = { name: "Farhan", phone: "98xxxxxx22" };
const s: Status = "SHIPPED";
const x: IdOrStatus = "OD-1";
console.log(item.qty * item.price, c.name, s, x);

Output

500 Farhan SHIPPED OD-1

Wrong Property

Example

Indexing with a property that does not exist is TS2339.

type Order = { id: string; status: string };
type Amount = Order["amount"];

Compiler output (tsc)

Line 2: error TS2339: Property 'amount' does not exist on type 'Order'.

Practice

Exercise: Given const PLANS = [{ name: "Basic", price: 199 }, { name: "Pro", price: 499 }] as const; create a type PlanName equal to "Basic" | "Pro" without writing the names again.

Show answer
const PLANS = [{ name: "Basic", price: 199 }, { name: "Pro", price: 499 }] as const;
type PlanName = (typeof PLANS)[number]["name"]; // "Basic" | "Pro"
const plan: PlanName = "Pro";
console.log(plan);