skip to content
Alvin Lucillo

Dynamic prop with enum

/ 1 min read

💻 Tech

To use your enum properties as the keys of your object, you need to use square brackets [] to signify that the key is an expression that’s dynamically evluated. Without it, it will be treated as literal values and cause an error.

enum StatusDeLoja {
  Ativo = 'Ativo',
  Inativo = 'Inativo'
}

const mapStatusAula = {
  [StatusDeLoja.Ativo]: {bgColor: "verde", fontColor: "branco"},
  [StatusDeLoja.Inativo]: {bgColor: "azul", fontColor: "preto"} 
}

for ( let i in mapStatusAula) {
  console.log(mapStatusAula[i]);
}

Code in action in Typescript playground