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

174
Views
Best way to cast an object to a TypeScript Enum Value

Is there an easy/best practice way to cast an any value to a TypeScript Enum and throw an exception if there is no value.

As an example

You have an express request object and are using the query.option value. Your application knows it only has two valid states a|b. However, the reality of the internet and request object is that it can be many things (undefined, a, b, foo).

enum OPTIONS_ENUM {
  a = 'a',
  b = 'b'
}

function handleRequest(req: Request): OPTIONS_ENUM {
  // This will error because query.option is an any
  return OPTIONS_ENUM[req.query?.option]
}

What I have been doing seems a little verbose. I have a "cast" function next to each enum that will throw if the ENUM does not have a value.

function castToOptionsEnum(option: any): OPTIONS_ENUM {
  if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
    throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`)
  }
 
  // @ts-ignore
  return OPTIONS_ENUM[option]
}

function handleRequest(req: Request) {
  // This will error because the option query is unknowable 
  return castToOptionsEnum(req.query?.option)
}

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

0

you can "simply" cast option to OPTIONS_ENUM when accessing OPTIONS_ENUM in castToOptionsEnum:

function castToOptionsEnum(option: any): OPTIONS_ENUM {
    if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
        throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`);
    }

    return OPTIONS_ENUM[option as OPTIONS_ENUM];
}

This will remove any compile errors (I would suggest to remove // @ts-ignore aswell, since it "hides" compile errors - but that's up to you ^^).

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!