Mapped Types Preserve Tuple Positions

Map over tuple keys so each element keeps its position literal, then build indexed rows and read the preserved tuple length.

TypescriptData Integrity

Code

typescriptsnippet
26 lines
type Indexed<T extends readonly unknown[]> = {
  [K in keyof T]: { position: K; item: T[K] };
};

// A mapped type over keyof T keeps each tuple position literal.
type Slots<T extends readonly string[]> = {
  [K in keyof T]: { slot: K; label: T[K] };
};

const pair = ['open', 200] as const;
const rows: Indexed<typeof pair> = [
  { position: '0', item: 'open' },
  { position: '1', item: 200 },
];

console.log(rows.map((row) => row.position + ':' + String(row.item)).join(','));

const slots: Slots<['id', 'name']> = [
  { slot: '0', label: 'id' },
  { slot: '1', label: 'name' },
];

console.log(slots.map((slot) => slot.slot + '=' + slot.label).join(','));

const tupleLength: 2 = rows.length;
console.log('length', tupleLength);

Output

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

0:open,1:200
0=id,1=name
length 2

Inside the code

Module-level bindings hold the data — pair — with no function scope in between.

Applying it

Running the file prints labeled results such as length — each operation’s effect is visible in the output.

Statements that matter

[K in keyof T]: { position: K; item: T[K] };
[K in keyof T]: { slot: K; label: T[K] };
const pair = ['open', 200] as const;

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `pair`.