Object.keys Widens Keys To Strings
Object.keys returns string[] and loses the key union; a small keysOf generic restores keyof T so loop variables stay precisely typed.
Code
const config = { host: 'localhost', port: 8080, retries: 2 };
// Object.keys 的静态类型是 string[]:编译器不知道键的联合
const plainKeys: string[] = Object.keys(config);
console.log('plain:', plainKeys.join(', '));
console.log('count:', plainKeys.length);
// 通用助手把结果收窄回 keyof T
function keysOf<T extends object>(value: T): (keyof T)[] {
return Object.keys(value) as (keyof T)[];
}
for (const key of keysOf(config)) {
// key 的类型是 'host' | 'port' | 'retries':取值无需断言
console.log(key, '=', config[key]);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
plain: host, port, retries
count: 3
host = localhost
port = 8080
retries = 2How it works
Object.keys Widens Keys To Strings is built around the function keysOf.
Repetition is confined to for (const key of keysOf(config)) — the rest of the file is straight-line.
Applying it
Running the file prints labeled results such as plain:, count: — each operation’s effect is visible in the output.
Statements that matter
return Object.keys(value) as (keyof T)[];
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `keysOf` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.