Javascript / Typescript中具有枚举的多属性循环对象文字

icomxhvb  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(137)

有没有办法在key和value是不同枚举的对象常量中循环?
例如:下面是一个检查收货产品类型的函数,但是有几个条件,如何缩短,写得更优雅?

export enum ProductType {
  CreditCard = 'credit-card',
  PersonalLoan = 'personal-loan',
  RealStateFinancing = 'real-state-financing',
  AutoLoan = 'auto-loan',
  BankAccount = 'bank-account',
  BusinessLoan = 'business-loan',
  Broker = 'broker',
  CardMachine = 'card-machine',
  CryptoBroker = 'crypto-broker',
}
export enum ProductTypeSlugEndpointApi {
  CreditCard = 'cartoes-de-credito',
  PersonalLoan = 'emprestimos',
  RealStateFinancing = 'financiamentos-imobiliarios',
  AutoLoan = 'financiamentos-veiculos',
  BankAccount = 'contas',
  BusinessLoan = 'emprestimos-pjs',
  Broker = 'corretoras',
  CardMachine = 'maquinas-cartoes',
  CryptoBroker = 'corretoras-criptomoedas',
function MappingProductTypeToEndpointApi(type: ProductType) {
  const endpoints = {
    [ProductType.CreditCard]: ProductTypeSlugEndpointApi.CreditCard,
    [ProductType.PersonalLoan]: ProductTypeSlugEndpointApi.PersonalLoan,
    [ProductType.RealStateFinancing]:
      ProductTypeSlugEndpointApi.RealStateFinancing,
    [ProductType.AutoLoan]: ProductTypeSlugEndpointApi.AutoLoan,
    [ProductType.BankAccount]: ProductTypeSlugEndpointApi.BankAccount,
    [ProductType.BusinessLoan]: ProductTypeSlugEndpointApi.BusinessLoan,
    [ProductType.Broker]: ProductTypeSlugEndpointApi.Broker,
    [ProductType.CardMachine]: ProductTypeSlugEndpointApi.CardMachine,
    [ProductType.CryptoBroker]: ProductTypeSlugEndpointApi.CryptoBroker,
  }

  return endpoints[type] || ProductTypeSlugEndpointApi.Default
}
iqxoj9l9

iqxoj9l91#

修改object的枚举类型,keyof typeof就能做到:

const Product = {
      CreditCard : 'credit-card',
      PersonalLoan : 'personal-loan',
      NotInEndPoints:"notinendpoints"
    } as const
    
    const EndPoints = {
      CreditCard : 'cartoes-de-credito',
      PersonalLoan: 'emprestimos',
        Default:'Default'
    } as const
    
    type TProduct = keyof typeof Product
    type TEndPoints = keyof typeof EndPoints
    
    function newMapp(type :  TProduct)
{
    return Object.keys(EndPoints).includes(type)? EndPoints[type]: EndPoints["Default"]
}

    console.log(newMapp("CreditCard")) // returns "cartoes-de-credito" 
    console.log(newMapp("NotInEndPoints")) //returns "Default"

相关问题