Indexed Access Types Read Field Types

Derive field types with indexed access types, write a generic getField helper, and index the whole object with keyof.

TypescriptData Integrity

Code

typescriptsnippet
27 lines
type Order = {
  id: string;
  total: number;
  customer: { name: string; vip: boolean };
};

// Indexed access types read a property type from another type.
type OrderId = Order['id'];
type Customer = Order['customer'];
type OrderValue = Order[keyof Order];

function getField<T, K extends keyof T>(record: T, key: K): T[K] {
  return record[key];
}

const order: Order = {
  id: 'o-1',
  total: 99.5,
  customer: { name: 'Ada', vip: true },
};

const id: OrderId = getField(order, 'id');
const total: number = getField(order, 'total');
const customer: Customer = getField(order, 'customer');

const values: OrderValue[] = [id, total, customer];
console.log(id, total, customer.name, values.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

o-1 99.5 Ada 3

How it works

Indexed Access Types Read Field Types comes down to the function getField.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Key statements

function getField<T, K extends keyof T>(record: T, key: K): T[K] {
return record[key];
}

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `getField` at load time.