
管理枚举值的工具
在业务中,我们经常需要维护一些枚举值,如状态、类型,这些枚举值包含 key: 唯一键(一般为英文)、value: 值(对应后端存储的数据)、label: 中文名(用于展示)。
之前我会这样去维护这些枚举值:
export enum STATUS { // key -> value TODO = 1, PENDING = 2, DOnE= 3, } export const STATUS_TEXT = { // key -> value -> label [STATUS.TODO]: "todo", [STATUS.PENDING]: "pending", [STATUS.DONE]: "done", }; 但是这样的维护方式有以下几个问题:
STATUS_TEXT 的 key 被转为 string 而非 number, 需要转换STATUS_TEXT[STATUS.TODO]因此我总结了 B 端场景下的以下这些常见使用场景:
{ label: string; value: string | number }[] 这样的数据该函数工具封装了以上业务场景的方法,方便维护枚举值,并且TS 支持 key 值的枚举推断
npm i @xliez/x-enum # or yarn add @xliez/x-enum # or pnpm add @xliez/x-enum import { Select } from "antd"; import { xEnum } from "@xliez/x-enum"; const TypeEnum = xEnum({ TODO: [0, "待办"], PENDING: [1, "处理中"], DONE: [2, "已完成"], }); // 1. 生成 select 组件 options const App = () => { return ( <> <Select label="select" name="select" optiOns={TypeEnum.genOptions()} /> </> ); }; // 2. 根据 key 取 value const value = TypeEnum.TODO.value; // 支持 TS 推断 // or const value = TypeEnum.valueByKey("TODO"); // 3. 根据 key 取 label const label = TypeEnum.TODO.label; // 支持 TS 推断 // or const label = TypeEnum.labelByKey("TODO"); // 4. 根据 value 取 label const label = TypeEnum.labelByValue(0); // 5. 根据 value 取 key const key = TypeEnum.keyByValue(0); // 6. 获取所有的 key const keys = TypeEnum.keys; // 7. 获取所有的 value const values = TypeEnum.values; // 8. 获取所有的 label const labels = TypeEnum.labels; 1 paledream OP 欢迎大家 star和反馈 |
2 vaporSpace 2023 年 3 月 16 日 我之前也写了类似的,但你设计的更好,如果需要这个枚举的 ts 类型要怎么搞呢 |
3 Trim21 2023 年 3 月 16 日 你列出来的有几个功能是 ts 的 enum 原生支持的... ```ts enum STATUS { // key -> value todo = 1, pending = 2, dOne= 3, } console.log(STATUS[STATUS.todo]); console.log(STATUS['todo']); console.log(STATUS); ``` |
4 paledream OP @Trim21 是的,TS enum 的反向映射支持了 value -> key ,但也因为这个特性,key 和 value 实际都是 key ,所以无法使用类似 `Object.keys` 快速生成 Select options |
5 paledream OP @vaporSpace 是类似这样的类型支持吗 ```ts enum EmployeeStatus { } const F: EmployeeStatus = EmployeeStatus.xxx ``` 目前还不支持,后续我思考下 |
6 Trim21 2023 年 3 月 16 日 via Android @paledream 可以参考下 https://github.com/sinclairzx81/typebox 的 type helper “Static” |