Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda