Suppose I have a class as follows:
class Company {
name: string;
url: string;
address: string
constructor() {
}
}
I then retrieve an object from a database which I know contain some or all of the properties of my class eg
{name: "Acme", url: "www.acme.com"}
Is there a way that I can automatically construct my class from the object?
At the moment, I know I can do something like:
const company = new Company();
const object = {name: "Acme", url: "www.acme.com"}; // in reality retrieve from database
for (const key in object) {
if (key == "name") {
company.name = object[key];
}
if (key == "url") {
company.url = object[key];
}
}
But this is not very elegant and become unwieldy over a larger volume of object properties.
Is there an automatic way to do this?
Object.assign?name: string;doesn't actually do anything. It's erased at compile time. You need to assign a default value to your members, then useObject.keyson your object, and copy things over from your db result object.