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

148
Visualizações
Why can't I iterate over the properties of a class before creating an instance?

Can someone explain to me why I can't iterate over the properties (edit: falsely wrote prototypes first) of a class without creating an instance of it? A stupid little example would be:

export class Animal {
  name: string;
  colour: string;

  constructor(init: string[]) {
    this.name = init[0];
    this.color = init[1]
  }
}

Now, somewhere else in the program (long before the first book is "created"), I would like to do this:

for (const key in  Object.keys(Animal) {
  // here I would expect to iterate over the keys 'name' and 'colour' so I can do something like:
  console.log(Animal[key]);
}

I'm aware, that it's not possible (previous post here and also according to MDN). But I don't understand the provided explanations. Could you explain to me why this is the case?

And, as a follow-up, how would I handle such a situation? Should I create an external interface/type that I loop over? I would generally like to have a single place that "holds" my animal properties.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because the properties of Animal are non-enumerable as can be seen in this example:

Object.getOwnPropertyDescriptors(Animal)

{
  "length": {
    "value": 1,
    "writable": false,
    "enumerable": false,
    "configurable": true
  },
  "name": {
    "value": "Animal",
    "writable": false,
    "enumerable": false,
    "configurable": true
  },
  "prototype": {
    "value": {},
    "writable": false,
    "enumerable": false,
    "configurable": false
  }
}

If you set the properties in the class to static they become enumerable. Alternatively you can iterate them this way:

for (const key in  Object.getOwnPropertyDescriptors(Animal)) {
  console.log(Animal[key]);
}
about 4 years ago · Juan Pablo Isaza 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