Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP / Typescript - is it possible to optimize code when class constructor has an interfaced object as param?

I'm new to typescript and my code has many repetitions of references (data1, data2, data3...).

export interface ProjectInterface{
  data1: string;
  data2: string;
  data3: number;
}

export class Project {
  data1: string;
  data2: string;
  data3: number;

  constructor(obj: ProjectInterface) {
    this.data1 = obj.data1;
    this.data2 = obj.data2;
    this.data3 = obj.data3;
  }
}

I know i could pass data1, data2... inside constructor but it's not handy when you have a lot of params.

Is there a clean workaround to keep the Interface has single entry point for references?

like image 716
sebap Avatar asked Aug 06 '26 10:08

sebap


1 Answers

i'd like to avoid repeating variables declarations in Project Class and automatize the initialization

While this certainly won't cut it in all circumstances, in your case you could use Object.keys to iterate over own properties of obj, while also performing some basic type-checking:

constructor(obj: ProjectInterface) {
    Object.keys(obj).forEach(key => {
        if (this.hasOwnProperty(key) && typeof this[key] == typeof obj[key]) {
            this[key] = obj[key];
        }
    });
}

This however requires that you also initialize your properties to a sensible default value, as hasOwnProperty will return false otherwise.

Note the ES6 arrow function that preserves the correct lexical scope of this.

like image 173
John Weisz Avatar answered Aug 09 '26 00:08

John Weisz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!