0

Is there any way to loop inside my object literal where key and value are different enums for each?

For ex: below is the function that performs checking the type of received product, but there are several conditions. How to shorten and write more elegantly?

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
}

1 Answer 1

1

change your enum for object, and keyof typeof does the trick :

    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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.