Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!