3 ms·
An approach I've seen is to have each class extend from some abstract base class (I know, OO blech) that looks like this: abstract class AbstractClassObjec
by ubertaco 10y ago
An approach I've seen is to have each class extend from some abstract base class (I know, OO blech) that looks like this:
abstract class AbstractClassObject {
constructor(json?: any){
if (json){
this.updateFromJSON(json)
}
}
public updateFromJSON = (json: any): this => {
Object.assign(this, json);
return this;
}
}
That gives you the "magic" just by extending the base, while also allowing custom behavior for a given class (by overriding updateFromJSON).
- wereHamster 10y agoThat only works for primitive types. As soon as you start using classes and sumtypes then you need an explicit parser. I wrote one for a client about a year ago. It took a lot of effort but well worth it.
- aj0strow 10y agoYeah but assigning doesn't really work for nested classes. class Post { id: string; user: User; // <- should be typeof User } I was hoping for something like Golang json.Unmarshal.