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

I have a JSON containing anonymous objects that go to my client side. Is there a built-in mechanism or an external library for converting these anonymous objects to strongly typed TypeScript objects? Is there something like AutoMapper for this?

My objects are complex, with complex types as properties.

+6
source share
3 answers

Get sample data and put 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

You will now 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 quotation marks:

 interface Person { name: string; height: number; pets: { name: string; species: string; }[]; } 
+8
source

I recently created an AutoMapper implementation in TypeScript / JavaScript for this particular scenario. I put the code in GitHub ( AutoMapperTS ). You can also use the library directly using the automapper-ts NPM package or automapper-ts Bower package.

The library is almost fully documented. In addition, there are already quite a lot of Jasmine unit tests (code coverage of more than 90%). They should provide you with some explanation of the need.

I hope this library meets your needs. If you have any questions and / or comments, please feel free to contact me!

Happy coding!

+3
source

I was looking for an easy way to convert json data from a web service to an interface. Did not find what I need, but here is my solution. Noticed that I added the "Pet" interface and added another pet to your json. It was also necessary to specify the anonymous object as "any". You can cut / paste this into the TypeScript site ( http://www.typescriptlang.org/play/index.html ) to see the results. Hope this helps.

 let header = document.createElement("div"); header.textContent = "Test"; document.body.appendChild(header); var people:any = [ { "name": "bob", "height": 150, "pets": [{ "name": "spot", "species": "dog" }, {"name" : "violet", "species": "shark"}] }, { "name": "jane", "height": 142, "pets": [{ "name": "lucy", "species": "cat" }] } ]; interface Pet { name: string; species: string; } interface Person { name: string; height: number; pets: Array<Pet> } class Foo { convertToObject = (person: Person) => person; } var person = new Foo().convertToObject(people[0]); let div = document.createElement("div"); div.textContent = `hey ${person.name} I see you have ${person.pets.length} pet`; document.body.appendChild(div); 
+1
source

Source: https://habr.com/ru/post/952757/


All Articles