Schema types a how to use it #1437
Replies: 1 comment
-
This is a great question! Backing up a bit, the expectation of this library is to help you consume types from your API. So by its nature, it will be most-heavily used while sending/receiving data from an external source. That’s why openapi-fetch was created—to reduce boilerplate code while fetching to/from your API (and was designed in such a way that it can be wrapped by many libraries, such as React Query). Beyond this, the assumption is that your core business logic is structured in a way that makes the most sense to the application. Having an API dictate the props passed to your component is a slight anti-pattern as a general rule, because an external API can’t take responsibility for how your internal biz logic should/shouldn’t work. So as a general rule, redeclaring your types manually is probably a good idea, because then, say, you could release a V2 of your API, or even pull the data from other sources, and then it’s not permanently attached to one single API’s historical data structures. But maybe there are shared types that make sense to export, e.g. your API has a import { components } from './my-schema';
export type User = components["schemas"]["User"]; Then, externally, referring to type So to condense that down into loose recommendations:
This just explains some of the philosophy/reasoning with this library. The initial example is contrived and just shows people how it works from a TypeScript perspective, but don’t take that as advice. Follow your gut—if something feels like too much work, it probably is! 🙂 |
Beta Was this translation helpful? Give feedback.
-
Hi, I am dealing with the question of how to correctly use the types returned by the API.
If I call the API, the result is returned typed, that's actually cool.
But, I need to put the returned data somewhere and I don't know how to simply get the type there. For example, a component that has props of a certain type (same as the data returned from the API).
There is an example on the website
This is of course possible, so I should for example
But I wouldn't want to write such a notation manually, because I have hundreds of such types in the current API.
Is there any way to write it better or... maybe just a TypeScript question, can't it be written so that I just type
MyApi.
and get help for all types?Maybe my question is related to this PR:
#1414
Thanks
Beta Was this translation helpful? Give feedback.
All reactions