array enum 的准替代方案(改进版)

本文介绍了一种使用TypeScript实现枚举增强的方法,通过抽象类和泛型为枚举类型增加value和label映射功能,方便获取枚举项的值和标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义类
export interface EnumItem {
  value: number | string;
  label: string;
  [x: string]: any;
}

export default abstract class Enum {
  public static states: readonly EnumItem[]

  public static get value (): EnumFn<typeof Enum, 'value'> {
    const res: any = {}
    this.states.forEach(v => {
      res[v.value] = v
    })
    return res
  }

  public static get label (): EnumFn<typeof Enum, 'label'> {
    const res: any = {}
    this.states.forEach(v => {
      res[v.label] = v
    })
    return res
  }
}

type EnumFn<S extends typeof Enum, K extends keyof EnumItem> = Record<S['states'][number][K], EnumItem>;
实际类
export enum IsoState {
  init = 0x01,
  check = 0x02,
  uploading = 0x03,
  failure = 0x04,
  finish = 0x05,
  delete = 0x06,
  notexist = 0x07,
  attached = 0x08
}

export class IsoStateEnum extends Enum {
  public static states = [
    { value: IsoState.init /* 也可以自定义 */, label: '初始', desc: 'sss' },
    { value: IsoState.check, label: '检测中' },
    { value: IsoState.uploading, label: '上传中' },
    { value: IsoState.failure, label: '失败' },
    { value: IsoState.finish, label: '已完成' },
    { value: IsoState.delete, label: '删除中' },
    { value: IsoState.notexist, label: '已删除' },
    { value: IsoState.attached, label: '已挂载' }
  ] as const

  public static value: EnumFn<typeof IsoStateEnum, 'value'>
  public static label: EnumFn<typeof IsoStateEnum, 'label'>
}

测试效果
console.info(IsoStateEnum.label.上传中.label)
console.info(IsoStateEnum.value[IsoState.attached].label)
console.info(IsoStateEnum.value[1].label)

结语
  1. 初步实现了数组枚举 ts 代码提示
  2. 无法实现自动填充 value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值