TS枚举最佳最佳实践
2024/11/30小于 1 分钟
TS枚举最佳最佳实践
定义枚举工厂类
type EnumFactoryValue<T, K> = { value: T } & K;
export default class EnumFactory<T extends string | number, K = { label: string }> {
enumObj: Map<T, EnumFactoryValue<T, K>>;
list: EnumFactoryValue<T, K>[];
constructor(enumMap: Map<T, K>) {
this.enumObj = new Map();
enumMap.forEach((item, key) => {
this.enumObj.set(key, { ...item, value: key });
});
this.list = Array.from(this.enumObj.values());
}
valueOf(val: T): EnumFactoryValue<T, K> {
const result = this.enumObj.get(val);
if (result) {
return result
} else {
throw new Error(`无效的枚举值: ${val}`);
}
}
valueOfByField<F extends keyof K>(value: K[F], field: F): EnumFactoryValue<T, K> {
const res = this.list.find((item) => item[field] === value);
if (res) {
return res
} else {
throw new Error(`无效的枚举值: ${value}`);
}
}
}定义枚举类型
enum Type {
Success = 'success',
Error = 'error',
Warning = 'warning',
}
const typeEnumData = new EnumFactory(new Map([
[Type.Success, { label: '成功' }],
[Type.Error, { label: '错误' }],
[Type.Warning, { label: '警告' }],
]));
enum Status {
Success = 'success',
Error = 'error',
Warning = 'warning',
}
const statusEnumData = new EnumFactory<Status, { label: string, color: string }>(new Map([
[Type.Success, { label: '成功', color: '#00ff00' }],
[Type.Error, { label: '错误', color: '#ff0000' }],
[Type.Warning, { label: '警告', color: '#ffff00' }],
]));项目中使用
下拉列表
<template>
<ElSelect>
<ElOption v-for="item in typeEnumData.list" :key="item.value" :value="item.value" :label="item.label" />
</ElSelect>
</template>
<script setup type="ts">
import { typeEnumData } from '@/typeData'
</script>在表格中使用
<template>
<ElTable>
<ElTableColumn prop="type" label="类型" width="100" >
<template #default="{row }">
<ElTag :color="statusEnumData.valueOf(row.type).color" >{{ typeEnumData.valueOf(row.type).label }}</ElTag>
</template>
</ElTableColumn>
</ElTable>
</template>
<script setup type="ts">
import { statusEnumData } from '@/typeData'
</script>