Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda