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

138
Views
Cannot define string enum typescript as string is not assignable
enum Cat {
    cat1 = 'cat1',
    cat2 = 'cat2',
    cat3 = 'cat3',
    cat4 = 'cat4',
    cat5 = 'cat5'
}
const category: Cat = 'cat' + cat

Why do I get a typescript error for that? cat is a number, so category is a string. But I want to define some specific string values for this variable.

Type 'string' is not assignable to type 'Cat'.
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I assume you want category to be one of Cat, not the enum itself. so

const cat = 4;
const category = Cat[`cat${cat}`] // category: Cat.cat4

This also gives you type safety if trying to access a number out of range. playground

enum Cat {
    cat1 = 'cat1',
    cat2 = 'cat2',
    cat3 = 'cat3',
    cat4 = 'cat4',
    cat5 = 'cat5'
}

const cat = 4;
const category = Cat[`cat${cat}`]

const cat6 = 6;
const category6 = Cat[`cat${cat6}`] // Property 'cat6' does not exist on type 'typeof Cat'.
about 4 years ago · Santiago Trujillo Report

0

Typescript cant ensure that cat is 1,2,3,4, or 5 since it could also be someThingElse. Therefore you have to tell typescript that you are sure its gonna be of type Cat

The issue here is that the compiler wont allow 'cat' + someVar to be used as type Cat.

Please be cautious when using this, since you essentially overwrite the compilers error. You really need to make sure that whatever you're doing before will always be a valid cat.

enum Cat {
  cat1 = 'cat1',
  cat2 = 'cat2',
  cat3 = 'cat3',
  cat4 = 'cat4',
  cat5 = 'cat5',
}
const category: Cat = (('cat' + cat) as Cat);
enum Cat {
  cat1 = 'cat1',
  cat2 = 'cat2',
  cat3 = 'cat3',
  cat4 = 'cat4',
  cat5 = 'cat5',
}

// this would be of however [Cat.cat1, Cat.cat2 ...] would be a lot safer. 
// I would generally suggest not tot use dynamic enum values like this.
for (const i of [1,2,3,4,5]) {
  const category: Cat = (('cat' + i) as Cat);
}

// the compiler would allow this as well, since you ensure that you know the type is going to be if type Cat
for (const i of ['dog']) {
  const category: Cat = (('cat' + i) as Cat);
}
about 4 years ago · Santiago Trujillo 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!