how can I specify the return type of the response of API response
For example I want to do something like this
6 Replies
- This type is designed to automatically infer and define the data types used within Hono applications.
- It eliminates the need for manual type declarations, making development more efficient and reducing the risk of type-related errors.
- Hono analyzes the structure and content of your data to determine its underlying types.
- This includes identifying objects, arrays, primitives (like strings, numbers, booleans), and more complex structures.
- Hono infers the appropriate TypeScript types for your data based on the analysis.
For example, if your data contains an object with certain properties and values, Hono might infer an interface type that describes those properties and their types.
The thing is I want to have control over the API responses to define for example this type
and I want to enforce that on every single route, just so I don't forget to write those and to stay semantic as possible in the responses so then in the development time, I would need less time writing unit-tests and the typescript compiler will let me know if I violated this, which I'm not saying I shouldn't write unit tests defiantly I should but this will make my development easier to manages especially If I'm working with a team that isn't that solid to grasp these points
Got it, in that case, you can do following
That's perfect thanks
Okay I'm using it inside
createMiddleware
how can I do that TypedResponse<LoginResponse | ErrorResponseType>
this is my typed definition
You can't apply any custom type for custom middleware. Here is the reason,
Unlike the previous solution, the router has the 'HandlerInterface' type,
H<E2, P, I, R>
. Here R is HandlerResponse<any>
which uses TypedResponse<>. That's why a custom response can be attached.
But the middleware return typed MiddlewareHandler<E, P, I>
where E stands for Environment, P stands for Path (always string), and I stands for Input which can be further typed for inand out
If you see the MiddlewareHandler it doesn't have R so it can't be extended or can't be applied any custom type for return.Ah okay thanks