Home > Mobile >  Cannot define string enum typescript as string is not assignable
Cannot define string enum typescript as string is not assignable

Time:12-22

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'.

CodePudding user response:

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'.

CodePudding user response:

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);
}
  • Related