I have a class
export class Example {
id: number = 0;
a: string = '';
b: string = '';
constructor(data: any) {
Object.keys(data).filter(key => key in data).forEach((key: string) => this[key] = data[key]);
return this;
}
}
I want to be able to send an object in the constructor, and based on that object it will assign the values in which the key matches the property of the class. This is because I might send an object which has additional key properties, but I do not want to put in my class the values that are not defined in my class. This is why I don’t use Object.assign(this, data);
because it will add additional properties to my class if the data object has them.
The problem with the code in the constructor above is that it’s not letting me use this[key]
, the error being Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Example'
. Can anyone help me with this?