Hacker News new | ask | show | jobs
by ubertaco 3482 days 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).
2 comments

Yeah 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.
That 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.