Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign new Class object through factory method but in a "generic" way?

I’m trying to create a class where I can pass optional parameters and through a factory method it assigns the values to the corresponding class attributes.

But I cannot access in a "generic" way any attributes on the class.

this[key] = object[key];

Is there a way to do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my object assignement:

p1: Person = new Person({ name: 'John Doe' });
p2: Person = new Person({ age: 2, height: 180 });

This is my Person class:

export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  constructor(data: Object) {
    this.factory(data);
  }

  factory(object: Object) {
    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        this[key] = object[key]; // <-- HERE IS MY PROBLEM
      }
    }
  }
}

I put my code on Stackblitz

>Solution :

There is an elegant solution for this. Add an indexer and use a more concrete parameter type. Look at this:

export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  [key: string]: any;

  constructor(data: Partial<Person>) {
    this.factory(data);
  }

  factory(object: Partial<Person>) {
    for (const key in object) {
      this[key] = object[key];
    }
  }
}

Update: That should work even without indexer:

factory(object: Partial<Person>) {
  Object.assign(this, object);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading