封装一个常用的Enum

前言

项目里面经常用到一些下拉框
尝试封装一个比较好用的Enum

文件目录

├── utils.ts 
├── index.txs
└── package.josn

代码

utils.ts

class Enum {
    static keys: string[];
    static values: Enum[];
    /**
     * call this function after declare all staic enum variable
     */
    static closeEnum(): void;
    /**
     * convert raw enum name to enum instance
     * @param key key(name) of enum member
     */
    static ofKey<T extends Enum>(key: string): T | undefined;
    /**
     * convert raw enum value to enum instance
     * @param value value of enum member
     */
    static of<T extends Enum>(value: string): T | undefined;
    /**
     * get { label, value } array
     */
    static options(): {
        label: string;
        value: string;
    }[];
    key: string;
    index: number;
    value: string;
    label: string;
    toString(): string;
}

export class Status extends Enum {
  static operating = new Status('01', '运营中')
  static waiting = new Status('02', '等待中')
  static debugging = new Status('03', '调试中')

  static _ = MachineStatusAll.closeEnum()
  constructor(value: string, label: string) {
    super()
    this.value = value
    this.label = label
  }
}

index.tsx

import { Status } from './utils 

useEffect(() => {
    console.log(Status.options())
    console.log(Status.of('03'))
    console.log(Status.ofKey('debugging'))
  }, [])

输出结果
封装一个常用的Enum_第1张图片

你可能感兴趣的:(typescript,前端,typescript)