mercredi 27 juillet 2016

TypeScript - passing a class as an argument, and reflection

I am writing a generic unmarshaller. It converts graph DB data to generated TypeScript (1.8.7) model classes. The input is JSON. The output should be an instance of a model class.

What's the right way to pass a class as a parameter and reach it's static members?

I've tried to write a method. Not sure if I am heading in the right direction, feel free to suggest different approaches.

public fromJSON(input: Object, clazz: typeof FrameModel): FrameModel
{
    clazz.graphPropertyMapping;
    clazz.graphRelationMapping;

    let result = {};
    ...
    return result;
}
...
SomeModel some = <SomeModel> unmarshaller.fromJSON({...}, SomeModel);

But when I tried to execute this on Plunker, I got execution errors with unuseful stacktrace.

The model looks like this:

import {TestPlanetModel} from './TestPlanetModel';
import {TestShipModel} from './TestShipModel';

export class TestGeneratorModel extends FrameProxy
{
    private vertexId: number;

    private const discriminator: string = 'TestGenerator';

    private const graphPropertyMapping: { [key:string]:string; } = {
        bar: 'boo',
        name: 'name',
        rank: 'rank',
    };


    private const graphRelationMapping: { [key:string]:string; } = {
        colonizes: 'colonizedPlanet',
        commands: 'ship',
    };

    boo: string;
    name: string;
    rank: string;

    public colonizedPlanet: TestPlanetModel[]; // edge label 'colonizedPlanet'

    public ship: TestShipModel; // edge label 'ship'

}

I haven't found much material on reflection and class handling in TypeScript.
I know how I would do this in Java.
I know how I would do this in JavaScript.
I understand that I might achieve similar results with decorators, but having fields or static fields seemed a bit simpler, for generated models.





Aucun commentaire:

Enregistrer un commentaire