On one hand, fetching data is a must in 99.99% of web projects. On the other hand, fetch
responses are not typed, or better stated, they return an object of type any
, and on the other (prosthetic) hand, it is a major pain to work on projects where you have to constantly log to the console the response objects because your project is either not a TypeScript project or other developers just plain didn't care about their fellow developers and never typed a thing.
If you agree with me so far, stay. If you don't agree, this is not for you.
The Problem In Detail
Typing a response is not straightforward. Even if Response.json()
were generic (it would accept the response type as a type argument), it still would be a pain. Why? Because the response type depends on the status code returned. A response with status code 200 OK carries different data than the response of the same URL with a 400 BAD REQUEST status code. Yes, we can go on: We could have different types for 401, 403, 201, 202, 503, etc.
So one URL, one fetch()
operation, but multiple possible return types that depend on the status code of the response. How to type this?
My Objective
If you have an idea on how to tackle this N-types-for-N-stauts-codes problem, please share, no worries, but I write this to sense the audience. My objective here is to know if it would be worth creating an NPM package that solves this problem.
Would you be interested in such a package? I have this working at work, but if there's interest, I can make a public NPM package out of it.
Let me know!! Thanks for reading.
Top comments (0)