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

170
Vistas
How do I assign class properties values based on existing keys in an object I send?

I have a class

export class Example {
    id: number = 0;
    a: string = '';
    b: string = '';

    constructor(data: any) {
        Object.keys(data).filter(key => key in data).forEach((key: string) => this[key] = data[key]);
        return this;
    }
}

I want to be able to send an object in the constructor, and based on that object it will assign the values in which the key matches the property of the class. This is because I might send an object which has additional key properties, but I do not want to put in my class the values that are not defined in my class. This is why I don't use Object.assign(this, data); because it will add additional properties to my class if the data object has them.

The problem with the code in the constructor above is that it's not letting me use this[key], the error being Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Example'. Can anyone help me with this?

about 4 years ago · Juan Pablo Isaza
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