How to create a TypeScript @Relationship decorator for a property?

0

Consider the following code:

export class Model {
    constructor(input: any) {
        this.deserialize(input);
    }

    deserialize(input: any): Model {
        Object.assign(this, input);
        return this;
    }
}

export class Body extends Model {
    Success: boolean;
    @Relationship Result: Result;
    //...
}

export class Result extends Model {
    Skip: number;
    Top: number;
    TotalCount: number;
    //...
}

The script receives a json and starts a new instance of class Body :

//...
let body = new Body({
    Sucess: true,
    Result: {
        Skip: 0,
        Top: 0,
        TotalCount: 20
        //...
    }
    //...
});

The deserialize method is used to copy the values of all enumerable properties of one or more source objects to a target object. It will return the target object.

In order for the Result property to start correctly, a change to the deserialize method is required:

deserialize(input: any): Model {
    Object.assign(this, input);
    this.Result = new Result(input.Result);
    return this;
}

The problem that the Model class is generic and can not implement the described solution.

I do not want to declare the deserialize method on each child class.

How can the problem be solved by using the @Relationship decorator?

    
asked by anonymous 10.02.2018 / 18:23

0 answers