JohnWeisz / TypedJSON

Typed JSON parsing and serializing for TypeScript that preserves type information.
MIT License
603 stars 64 forks source link

How about `fromJson` on decorated class? #110

Closed bukuta closed 5 years ago

bukuta commented 5 years ago

TypedJSON is a nice job and i look for it months.

How about adding a decorate like fromJson( or with other name)? If a static method fromJson is added on the decorated class, then the usage may be a little simpler and easier, like Person.fromJson(xxx) instead of TypedJSON.parse(xxx,Person)

// defines
@fromJson
@jsonObject
class Person {
    @jsonMember({ name: "first-name" })
    public firstName: string;

    @jsonMember({ name: "last-name" })
    public lastName: string;
}

// usages
let p1 = Person.fromJson({'first-name':'xxx', 'last-name':'yyy'});

What your opinion?

JohnWeisz commented 5 years ago

Hey @bukuta

Technically, this should be as simple as:

let p1 = new TypedJSON(Person).parse(...);

The problem with the proposed approach is that TypeScript doesn't support type augmentation based on decorators, hence it'll complain that your class does not have a static fromJson method.

Perhaps instead you could do something like:

class JSONInstantiable {
    public static fromJson(json: string) {
        return new TypedJSON(this).parse(...);
    }
}

And then extend this class to call fromJson in derived classes.

bukuta commented 5 years ago

Thanks for your reply and the solution. You are good man.