Skip to main content

枚举 转 Map 和 options

支持 TS 类型声明,可以方便的将枚举转换为 Map 和 options。

无需手动写 map 和 options,可以自动生成,并进行 type 推断。

使用效果

export enum TabEnum {
"xxx" = 1,
"xxx" = 2,
"xxx" = 3,
}
export const TabMap = enumToMap(TabEnum);
export const TabOptions = mapToOptions(TabMap);

Enum 转 Map

export const enumToMap: EnumToMapProps = (enums) => {
type KeyType = keyof typeof enums;
const keys = filter(Object.keys(enums), isNaN) as KeyType[];
return new Map(keys.map((key) => [enums[key], key]));
};

Map 转 options

export const mapToOptions = <MapKey, MapValue>(map: Map<MapKey, MapValue>) => [...map.entries()].map(([value, label]) => ({ value, label }));

全部代码

import { filter, isNaN } from "lodash-es";

type EnumToMapProps = <EnumType extends Record<string, unknown>>(enums: EnumType) => Map<EnumType[keyof EnumType], keyof EnumType>;
/** ## 枚举 转 Map
*
* ### Example
* ```
export enum TabEnum {
'xxx' = 1,
'xxx' = 2,
'xxx' = 3,
}
export const TabMap = enumToMap(TabEnum);
export const TabOptions = mapToOptions(TabMap);
* ```
*/
export const enumToMap: EnumToMapProps = (enums) => {
type KeyType = keyof typeof enums;
const keys = filter(Object.keys(enums), isNaN) as KeyType[];
return new Map(keys.map((key) => [enums[key], key]));
};

/** ### Map 转 options */
export const mapToOptions = <K, V>(map: Map<K, V>) => [...map.entries()].map(([value, label]) => ({ value, label }));