Object.keys Widens, Entries Restore Types

Object.keys returns string for typed objects, so a cast restores the union; Object.entries pairs each key with its value type for typed rebuilds.

TypescriptData Integrity

Code

typescriptsnippet
17 lines
const config = { retries: 3, timeoutMs: 1500 } as const;
type ConfigKey = keyof typeof config;

// keys 的返回被加宽成 string[]:直接索引进 typed 对象会被拒
const widened: string[] = Object.keys(config);
const keys = widened as ConfigKey[];
for (const key of keys) {
  console.log(key, config[key]);
}

// entries + 类型断言成元组数组:键与值一起收窄,重建时键不丢
const doubled = Object.fromEntries(
  (Object.entries(config) as [ConfigKey, number][]).map(
    ([key, value]) => [key, value * 2],
  ),
);
console.log(JSON.stringify(doubled));

Output

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

retries 3
timeoutMs 1500
{"retries":6,"timeoutMs":3000}

What powers the file

Repetition is confined to for (const key of keys) — the rest of the file is straight-line.

Everything operates on top-level bindings: config, keys, doubled.

One object literal carries retries, timeoutMs — every value is written inline.

Watch out for

  • All symbols it touches come from the language itself — nothing gets fetched.

Key statements

const config = { retries: 3, timeoutMs: 1500 } as const;
type ConfigKey = keyof typeof config;

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `config`, `keys`, `doubled`.