枚举数组类型,必须使用 as const 断言以保留字面量类型
枚举元组,建议使用 as const 修饰以获得最佳类型推断
Optional
options: EnumCreationOptions创建时的配置项
基础用法:
const statusList = [
{ label: '待处理', value: 1, color: 'orange' },
{ label: '已完成', value: 2, color: 'green' },
{ label: '已取消', value: 3, color: 'red' }
] as const
const statusEnum = createEnum(statusList)
// 基础查找操作 (O(1) 时间复杂度)
const label = statusEnum.getLabelByValue(1) // '待处理'
const value = statusEnum.getValueByLabel('已完成') // 2
const item = statusEnum.getItemByValue(1) // 完整对象
// 类型安全的属性访问
const color = statusEnum.getAttrByValue(1, 'color') // 类型推断为 'orange' \\| 'green' \\| 'red' \\| undefined
// 列表操作
const allLabels = statusEnum.getLabels() // ['待处理', '已完成', '已取消']
const allValues = statusEnum.getValues() // [1, 2, 3]
// 条件判断
const isValid = statusEnum.isValueInLabels(apiData.status, ['待处理', '已完成'])
const exists = statusEnum.has(1) // true
// 显示文本处理
const displayText = statusEnum.getDisplayTextByValue(1) // 如果有displayText则返回,否则返回label
配置化重复检查:
const statusList = [
{ label: '待处理', value: 1 },
{ label: '处理中', value: 2 },
{ label: '待处理', value: 3 } // label 重复
] as const
// 默认行为:只在开发环境检查
const enum1 = createEnum(statusList)
// 强制始终检查 (例如,用于生产环境启动脚本)
const enum2 = createEnum(statusList, { checkDuplicates: 'always' })
// 或使用 boolean 简写
const enum2b = createEnum(statusList, { checkDuplicates: true })
// 强制从不检查 (例如,用于特殊测试)
const enum3 = createEnum(statusList, { checkDuplicates: 'never' })
// 或使用 boolean 简写
const enum3b = createEnum(statusList, { checkDuplicates: false })
复杂枚举示例:
const userRoleList = [
{
label: '管理员',
value: 'admin',
displayText: '系统管理员',
permissions: ['read', 'write', 'delete'],
level: 1
},
{
label: '编辑者',
value: 'editor',
displayText: '内容编辑者',
permissions: ['read', 'write'],
level: 2
},
{
label: '访客',
value: 'guest',
permissions: ['read'],
level: 3
}
] as const
const roleEnum = createEnum(userRoleList)
// 获取权限信息
const permissions = roleEnum.getAttrByValue('admin', 'permissions')
// 类型推断为: ['read', 'write', 'delete'] \| ['read', 'write'] \| ['read'] \| undefined
// 检查角色级别
const level = roleEnum.getAttrByLabel('编辑者', 'level') // 2
创建类型安全的、不可变的枚举工具实例
该函数是创建EnumArray实例的推荐方式,返回的对象被冻结以确保不可变性。 EnumArray继承了Array,因此可以使用所有原生Array方法。