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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With