Typed entries Preserve Key Value Correlation

Type Object.entries helpers so iteration keeps each key correlated with its own value type instead of collapsing to a wide union.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
type Flags = {
  dark: boolean;
  limit: number;
  label: string;
};

function entriesOf<T extends Record<string, unknown>>(record: T): Array<[keyof T, T[keyof T]]> {
  return Object.entries(record) as Array<[keyof T, T[keyof T]]>;
}

const flags: Flags = { dark: true, limit: 10, label: 'beta' };
for (const [key, value] of entriesOf(flags)) {
  console.log(key, '=', value);
}

// 回调形式保留键与值的关联:K 决定 T[K]
function mapEntries<T extends Record<string, unknown>, R>(
  record: T,
  map: <K extends keyof T>(key: K, value: T[K]) => R,
): R[] {
  return (Object.keys(record) as Array<keyof T>).map((key) => map(key, record[key]));
}

const summary = mapEntries(flags, (key, value) => key + ':' + String(value));
console.log(summary.join(' | '));

// 键的联合类型在编译期可见
type FlagKey = keyof typeof flags;
const sample: FlagKey = 'limit';
console.log('sample key:', sample);

Output

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

dark = true
limit = 10
label = beta
dark:true | limit:10 | label:beta
sample key: limit

What the snippet does

The file repeats itself only inside for (const [key, value] of entriesOf(flags)).

All the work happens over top-level bindings: summary.

The top-level object literal pins dark, limit, label as plain values — no derivation, no imports behind them.

Applying it

The loop prints each flag on its own line (dark = true, limit = 10, label = beta), mapEntries joins them into dark:true | limit:10 | label:beta, and sample key: limit closes the run from the FlagKey constant.

Statements that matter

return (Object.keys(record) as Array<keyof T>).map((key) => map(key, record[key]));
const summary = mapEntries(flags, (key, value) => key + ':' + String(value));
return Object.entries(record) as Array<[keyof T, T[keyof T]]>;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `summary`.