0

I am writing a web service and I want to build out types that can be used by the client which is another repository. So, if I have something like:

export interface Device { name: string, address: number }

And I return this "shape" in a json payload, but I'd like to share the type definition with the client, what is the best way to do that? Do I need to create a new repository and publish a d.ts file as an npm package, then import that from the client? Or is there a better way?

Ira Klein
  • 425
  • 3
  • 6
  • You mentioned "create a new repository", do you have an existing client/utility repository for this web service? Or is it just a new repository because there's nothing relevant in `npm` to add it to? – Jeff Bowman Jun 08 '22 at 21:10
  • I'm just meaning do I need to make it a separate project and use npm to publish it, then install it into my server and then client projects, or is there a better way? – Ira Klein Jun 09 '22 at 11:45
  • So I found this article: https://stackoverflow.com/questions/65045106/share-types-between-client-and-server. Uses path mapping. Seems to compile fine, but my react-native app doesn't include it, so I get a runtime error unable to resolve module. – Ira Klein Jun 09 '22 at 12:08

1 Answers1

0

At the end of the day, you've got reusable code (types) consumed at compile time (types don't exist at runtime) and you need them to be available to both clients and servers during their separate compilation processes.

It doesn't really matter how you distribute the code—zip file, copy-paste, carrier pigeon—but for ubiquity and standardization I think it makes sense to make them available in an npm module. I don't know what you mean by a "better way"; this is just compile-time code sharing, the same way most of npm is filled with libraries of code to be shared at compile time.

I wouldn't go out of my way to make a separate module just for types, but I would consider a separate module just for pieces shared between client and server. This prevents you from mixing server-only code into your clients, assuming the server is open-source JS/TS in the first place. If you need to add any reusable bits—say, model objects, data validators or JSON utilities—those would have a natural place to go. Of course, on day 1 this might be mostly useful for types, but if client and server share concerns with types I think it's natural that those concerns would grow over time.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • Thanks for the advise. I have tried to avoid the npm route because of the extra steps of having to publish changes, then install them in the client side. I did extract the types (enums and interfaces) in separate files and have gotten the compilation to work, but I receive run time errors either on the client side or the server side depending on how I do it. I think I'll go with the npm path for now. – Ira Klein Jun 12 '22 at 12:49