Search code examples
javascriptreactjstypescriptenumsreact-typescript

Replace conditions with enum in Typescript


Having the following original code, it is a function which based on the value of toCheck is building a css class:

const computeSomething = (toCheck: string) => {
   return clsx('flex', {
     'flex-start': toCheck === 'FIRST',
     'flex-end': toCheck === 'LAST'
   });
}

The requirement is to use enum for toCheck, tried something but probably it's wrong:

export enum toCheck {
  FIRST = 'FIRST',
  LAST = 'LAST'
}

const computeSomething = (toCheck: string) => {
   return clsx('flex', {
     'flex-start': toCheck.FIRST,
     'flex-end': toCheck.LAST
   });
}

The error says:

Property 'FIRST' does not exist on type 'string'.

Any ideas?


Solution

  • The problem is that your toCheck is not referring to the (intended) enum due to your parameter being named the same (toCheck: string). Changing the name of either should solve the problem:

    export enum ToCheckEnum {
      FIRST = 'FIRST',
      LAST = 'LAST'
    }
    
    const computeSomething = (toCheck: string) => {
       return clsx('flex', {
         'flex-start': ToCheckEnum.FIRST,
         'flex-end': ToCheckEnum.LAST
       });
    }
    

    The convention is that enum/type should have Pascal case so I think this way is better.