Typescript: Object to class
You can use Object.assign
:
class C {
str:string;
num:number;
}
var o = JSON.parse("{\"num\":123, \"str\":\"abc\"}");
const instance:C = Object.assign(new C(), o);
I landed here wanting to create a class instance from an object literal. Object.assign()
works but it isn't type safe. Of course, if you have JSON source that's expected but I just wanted to instantiate a class with a known state.
From the TypeScript docs, a class also acts as a type. Thus, the following will work:
class C {
str: string;
num: number;
constructor(source: Partial<C>) {
Object.assign(this, source);
}
}
// Ok - all properties
const c1 = new C({
num: 123,
str: "abc"
});
// Ok - only some of the properties
const c1 = new C({
num: 123,
});
// Error: unknown property `unexpectedPropertyName`
const c2 = new C({
num: 123,
unexpectedPropertyName: "abc"
});