定义类
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)
结语
- 初步实现了数组枚举 ts 代码提示
- 无法实现自动填充 value