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.
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;
}[];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With