Best Ways to Share DTOs Between C# Backend and TypeScript Frontend

0
20
Asked By CreativeCoder93 On

I'm working on a small project that has a C# backend and an Angular frontend. I want to expose some simple Data Transfer Objects (DTOs), like ProductDTO, from the backend to the frontend through REST. I've created a ProductDto.cs file in my backend repository. I thought about using Nswag to generate a myApi.ts file and then create an npm package to upload to an internal package repository for the frontend to access. Does this sound like a good plan? However, I'm getting the feeling that using Nswag might be overkill since it also generates the entire backend schema along with the REST methods. Is there a simpler way to handle this?

5 Answers

Answered By BackendGuru77 On

If you look into .NET's built-in OpenAPI support, it might be beneficial. You can expose API definitions and generate a TypeScript client. If you're only concerned about the DTOs, you can tweak the generation settings so there's no need for a separate package. It can output the .ts file straight into your frontend project.

Answered By CodeExplorer42 On

For smaller projects, it’s fine to just generate the TypeScript types from your backend when needed. Sharing a package just adds unnecessary complexity.

Answered By TechSavvy88 On

You could definitely go with your plan, but for a small project, generating the TypeScript types on demand from the backend can work just as well. Sharing a packaged version is probably more effort than it's worth if only your frontend is going to use those DTOs.

Answered By FrontEndWizard On

In your case, if you're clearly separating the front and back ends, keeping JSON as the middle ground is solid. Just make sure your DTOs are structured well for the frontend to consume.

Answered By DevNinja101 On

Consider customizing the generation settings to fit your needs better. You can tweak Nswag to generate only what you want, like just the types and not the entire API client.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.