Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You are shadowing the enum by using the same name for your parameter. Use a different name for the enum and the parameter to avoid it. The idiomatic case for enums is PascalCase.

After that, just use a generic that extends the enum type and you should have no problems:

TS Playground link

declare function clsx (...args: unknown[]): void;

enum ToCheck {
  FIRST = 'FIRST',
  LAST = 'LAST',
}

const computeSomething = <T extends typeof ToCheck>(toCheck: T) => {
   return clsx('flex', {
     'flex-start': toCheck.FIRST,
     'flex-end': toCheck.LAST
   });
}

computeSomething(ToCheck); // ok
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

Why do you pass in toCheck as an argument? Just do this:

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


const computeSomething = (toCheck: ToCheckEnum) => {
  return clsx('flex', {
    'flex-start': toCheck === ToCheckEnum.FIRST,
    'flex-end': toCheck === ToCheckEnum.LAST
  });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!