首页  编辑  

枚举值和字符串的相互转换

Tags: /Node & JS/   Date Created:
NodeJS中,枚举值和字符串的相互转换:
export enum ContractstatusEnum {
  D = "Draft",
  P = "Pending",
  V = "Verified",
  R = "Reload"
}

export function toDesc(status: ContractstatusEnum): string | undefined {
  return ContractstatusEnum[status as keyof typeof ContractstatusEnum];
}

// 方法:将字符串转换为枚举值
export function fromDesc(desc: string): ContractstatusEnum | undefined {
  for (const key in ContractstatusEnum) {
    if (ContractstatusEnum[key] === desc) {
      return ContractstatusEnum[key as keyof typeof ContractstatusEnum];
    }
  }
  return undefined; // 如果找不到匹配的枚举值,返回undefined
}