Keyof typeof For Enum Like Maps
Derive union types from a frozen object with keyof typeof, keeping string literals and lookup tables in sync without a separate enum.
Code
const STATUS = {
idle: { label: 'Idle', retry: false },
running: { label: 'Running', retry: false },
failed: { label: 'Failed', retry: true },
} as const;
// keyof typeof:从值反推键的联合类型,映射表与字面量类型同源
type Status = keyof typeof STATUS;
type StatusMeta = (typeof STATUS)[Status];
function isRetryable(status: Status): boolean {
return STATUS[status].retry;
}
const statuses: Status[] = ['idle', 'running', 'failed'];
for (const status of statuses) {
const meta: StatusMeta = STATUS[status];
console.log(status, '->', meta.label, '| retry:', isRetryable(status));
}
// 拼错的状态名是编译错误
// const bad: Status = 'paused';Output
Captured from a sandboxed run of this snippet in the build pipeline.
idle -> Idle | retry: false
running -> Running | retry: false
failed -> Failed | retry: trueInside the snippet
Keyof typeof For Enum Like Maps reduces to the function isRetryable.
Iteration happens inside for (const status of statuses) — everything outside it runs once.
Putting it to use
The primary signature is function isRetryable(status: Status)
Core lines
type Status = keyof typeof STATUS;
return STATUS[status].retry;
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `isRetryable` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.