Hacker News new | ask | show | jobs
by aj0strow 3479 days ago
The easier imports solves my biggest issue with migrating an existing project over. I'd say TypeScript is "ready" now.

The last feature I'd want is an easy way to map nested json into classes rather than interfaces. Anyone know how?

1 comments

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).
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.