Need to assign porperties to the only defined from the interface if used with spread operator.
I am expecting a solution for using typescript constructor with spread operator.
For eg.
export interface IBrand {
id: string;
name: string;
}
export class Brand implements IBrand {
id: string;
name: string;
constructor(data: IBrand) {
this.id = data.id;
this.name = data.name;
}
}
this is one option so the moment when I call this class like this, no way how many members are there but I would be having only id, name
to final object.
new Brand({...data })
Case: But when I have 25+ keys to the data
export interface IBrand {
id: string;
name: string;
}
export class Brand implements IBrand {
id: string;
name: string;
constructor(data: Partial<IBrand>) {
Object.assign(this, data);
}
}
I am expecting not to write all properties again constructor. No matter it has 25 it would be just assigning that existing properties would be assigned. If data has section, genre
or any other property it would be ignored.
My 2nd snippet doesn't work.
This doesn't use the spread operator, but you could use the method from this answer
constructor(data: IBrand) {
for (let key in data) {
this[key] = data[key];
}
}
then instantiate...
new Brand(data);
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