How to describe return type of function which is result of call passed generic function

Interesting question, since I've experimented a lot with coding techniques in this area as a platform engineer, so I thought I'd share some suggestions.

I have found that generics on their own do not provide a full solution, or the most readable code. When dealing with API calls it can help to formulate requirements and provide layers with different responsibilities. Here is an example approach that I use in my own apps - expressed via React + Axios.

REQUIREMENTS

  • React views must get a typesafe experience when dealing with API payloads
  • Reliability and retries must be handled by shared classes used in multiple apps, eg to retry API calls, implement circuit breaker or whatever
  • Code must be simple and readable

CODE SNIPPETS

  • React view model uses typed API entities without casting and the UI renders this in a type safe manner. All views and view models get this experience.

  • Fetch class implements low level stuff and could be shared between multiple apps. At one point I used generics here and the code wss much less readable.

  • Service agent class. A simple adapter with methods that serve views in the most natural way. There are casts here but they are only in this layer.

  • In other places limited generics are used, eg to call axios.get<T>. However, using generics in many places with separate request and response types quickly gets messy.

CONCLUSION

Sometimes layering and separation of concerns provides the cleanest solution, rather than using generics too much. Out of interest the design is portable to any language, and I also use it for mobile apps:

  • Swift API Calls in iOS
  • Kotlin API Calls in Android

Of course, my code could be improved, eg to validate better before casting - perhaps service agents could manage that. But all developers in a software company would understand my code, which I think is the most important outcome.