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.
"id"and"name"as runtime values if you want something to happen at runtime. The easiest way to do this is to mention those keys in an array. (e.g. in TS3.4,(["id", "name"] as const).forEach(k => this[k] = data[k]);). The only way to avoid repeating the words"id"and"name"in the interfaces/classes and at runtime is to create a runtime constant array with those names in them and then derive the interface/class definitions from them (instead of the other way around which won't work) but that is a lot of type juggling just to avoid writing a few string literals.