Dynamically convert a JSON config into a Typescript Class

Viewed 1454

I have scoured the Net, I have read the typescript documents and looked at many answers here on stack overflow. None have given me enough insights on the following:

Using typescript I import a JSON file that looks like this:

[
    {
        "property" : "FristName",
        "type" : "string"
    },
    {
        "property" : "LastName",
        "type" : "string"
    },
    {
        "property" : "Age",
        "type" : "number"
    }
]

The property key is a class property and the type key denotes the property type.

Then I am attempting to write a class constructor that dynamically turns it at runtime into:

class Person {
    public FirstName: string;
    public LastName: string;
    public Age: number
{

The JSON array could potentially have an index of n object literals. The object literal structure is static and will always only have the two attributes attribute and type.

1 Answers

A good practice would be to create a PersonFactory class, with a public fromJSON method that accepts a JSON string and returns a Person instance.

import { Person } from "person";

export interface Spec {
  [index: number]: {attribute: string, type: "string" | string };
}

export class PersonFactory {
    fromJSON(spec: Spec): Person {
        return new Person(spec[0].attribute, spec[1].attribute);
    }
}

Use the factory as:

import { PersonFactory, Spec } from "factories";

const data: Spec = require("person_spec.json");

const person: Person = (new PersonFactory()).fromJSON(data);
Related