Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading