Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily create a strongly typed object from an anonymous object in TypeScript?

I have some JSON containing anonymous objects coming to my client-side. Is there some built-in mechanism or external library for converting these anonymous objects into strongly-typed TypeScript objects? Is there something like AutoMapper for doing this?

My objects are complex types, with complex types as properties.

like image 703
Ryan Shripat Avatar asked Aug 29 '13 17:08

Ryan Shripat


1 Answers

Get some sample data and place it in a .ts file:

var people = [
    {
        "name": "bob", "height": 150, "pets": [{ "name": "spot", "species": "dog" }]
    },
    {
        "name": "jane", "height": 142, "pets": [{ "name": "lucy", "species": "cat" }]
    }
];

Run tsc --declaration yourFile.ts

Now you'll have yourFile.d.ts:

declare var people: {
    "name": string;
    "height": number;
    "pets": {
        "name": string;
        "species": string;
    }[];
}[];

Replace declare var people: with interface Person, remove the trailing [], and (optionally) remove the quotes:

interface Person {
    name: string;
    height: number;
    pets: {
        name: string;
        species: string;
    }[];
}
like image 85
Ryan Cavanaugh Avatar answered Oct 05 '22 07:10

Ryan Cavanaugh