bhylu.com

Advertisements

TypeScript Indexed Access Types

An indexed access type selects a property type from another type. It keeps related declarations connected when a shared model changes.

How it works

The display layer needs the same count type as a Lot record, so Lot["packets"] expresses that dependency directly. An array element type can be selected with [number]. These are type operations and disappear from JavaScript. Do not confuse the notation with a runtime property read, which still needs a real object and may return undefined.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

type Lot = { code: string; packets: number };
type PacketCount = Lot["packets"];
type Lots = Lot[];
type OneLot = Lots[number];
const count: PacketCount = 5;
const lot: OneLot = { code: "PE-5", packets: count };
console.log(lot.code, lot.packets);

Expected result

PE-5 5

Both aliases are derived from the declared model, so a deliberate model change reaches dependent declarations. Combining indexed access with keyof is useful for generic property readers. For public APIs, keep names readable rather than stacking several type operations into an expression no one can explain.