← 中文资源

简体中文版本

keyof typeof 枚举式映射

用 keyof typeof 从冻结对象推导联合类型:字符串字面量与查找表保持同步,不必再单独维护一份 enum,拼错键会在编译期报错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

idle -> Idle | retry: false
running -> Running | retry: false
failed -> Failed | retry: true

实现说明

功能集中在函数 isRetryable上。 for (const status of statuses) 承担全部的逐项处理。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 isRetryable。

签名一览:function isRetryable(status: Status)

核心语句

type Status = keyof typeof STATUS;
return STATUS[status].retry;

代码示例

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';