You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中从数组值生成键值相同的字符串枚举

从国家ISO代码数组生成键值一致的字符串枚举

方法1:类型安全的动态推导(推荐)

利用TypeScript的const断言和对象推导,实现数组与枚举的自动同步,无需手动维护枚举项:

const countries = ['AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG'] as const;

// 生成键值完全对应的对象
const CountryObj = Object.fromEntries(countries.map(code => [code, code])) as {
  [K in typeof countries[number]]: K
};

// 导出类型和对象,模拟枚举的使用方式
type Country = typeof countries[number];
const Country = CountryObj;

使用时既可以通过Country.AF获取值,也能通过Country类型做类型约束,数组更新后类型和对象会自动同步。

方法2:脚本批量生成静态枚举

如果需要直接得到标准的枚举代码,可以写个简单的Node.js脚本批量生成:

const countries = ['AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG'];

// 拼接成枚举字符串
const enumString = `enum Country {
  ${countries.map(code => `${code} = '${code}'`).join(',\n  ')}
}`;

console.log(enumString);

运行脚本后,控制台会输出你需要的枚举代码,直接复制到项目中即可。这种方式适合数组固定不变的场景,避免手动逐个编写枚举项。

方法3:TypeScript 4.9+ 更简洁的约束写法

如果你的项目使用TypeScript 4.9及以上版本,可以用satisfies操作符简化类型约束:

const countries = ['AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG'] as const;

const Country = Object.fromEntries(countries.map(c => [c, c])) satisfies Record<typeof countries[number], typeof countries[number]>;

type Country = keyof typeof Country;

这种写法既能保证对象的键值完全匹配数组元素,又能自动推导准确的类型,代码更简洁。

内容的提问来源于stack exchange,提问作者biorubenfs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:20:06