Practices - Do you generate strongly-typed interfaces for your DTOs?
  v7.0 Posted at 6/03/2019 5:09 PM by Brendan Richards

Inevitably, our 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.

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.

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 (a.k.a. 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  
Figure: Good example - NSwag generates the boring work so that you don't have to.​



Figure: Good example: this client side api-access code from Jason Taylor's NorthwindTraders sample project has been generated by NSwag https://github.com/JasonGT/NorthwindTraders​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address: