Practices - Do you generate strongly-typed interfaces for your DTOs?

Last updated by Tiago Araújo [SSW] 6 months ago.See history

Inevitably any well-engineered Angular application will need to send and receive data from a service of some sort – usually a Web API. A common mistake people make when doing this is using typescript’s built in any type for these services, which offers no type safety whatsoever.

dtogs bad
Figure: Bad example - The "any" type is used as the DTO for this service. There is no type safety

One step better is to manually create interfaces for the DTOs. This gives type safety, but still means a lot of manual, tedious work to generate the interfaces.

dtogs ok
Figure: OK example - Manually coded interface ensures any object passed to the service is in the correct format

But this still doesn’t give safety over-the-wire – if the server side model changes, a developer has to remember to update it here, and hope that there are no typos. This is also extra effort to perform something mindlessly repetitive – something a machine is much better at doing. And we are programmers, right?

If your WebAPI has an OpenAPI (aka Swagger) specification, then the NSwag tools can build a complete Typescript client configured as an Angular injectable service - complete with:

  • HttpClient calls that return Observables
  • All defined endpoints implemented as methods in the service
  • All DTOs included as Typescript interfaces

nswag
Figure: Good example - NSwag generates the boring work so that you don't have to

northwind client
Figure: Good example - This client side api-access code from Jason Taylor's NorthwindTraders sample project has been generated by NSwag

Source: https://github.com/JasonGT/NorthwindTraders

We open source. Powered by GitHub