Benno
Benno
HHono
Created by Benno on 8/28/2024 in #help
Enforcing strict types for Hono's c.json() responses?
Is it possible to enforce strict typing for Hono's c.json() responses at a top level (hono.Handler<..>)? Currently, I can define expected response types like this:
type MyResponse = {someType: string};
type MyHandlerResponse = hono.HandlerResponse<MyResponse>;
type MyHandler = hono.Handler<any, any, any, MyHandlerResponse>
type MyResponse = {someType: string};
type MyHandlerResponse = hono.HandlerResponse<MyResponse>;
type MyHandler = hono.Handler<any, any, any, MyHandlerResponse>
This provides suggestions in c.json({...}), but doesn't raise a type error for mismatched types:
c.json('') // No type error, even though it should be an object. I get suggestions though, see video
c.json('') // No type error, even though it should be an object. I get suggestions though, see video
Hono's internal types for quick reference:
export type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>;

export type TypedResponse<T = unknown, U extends StatusCode = StatusCode, F extends ResponseFormat = T extends string ? 'text' : T extends JSONValue ? 'json' : ResponseFormat> = {
_data: T;
_status: U;
_format: F;
};
export type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>;

export type TypedResponse<T = unknown, U extends StatusCode = StatusCode, F extends ResponseFormat = T extends string ? 'text' : T extends JSONValue ? 'json' : ResponseFormat> = {
_data: T;
_status: U;
_format: F;
};
Example: https://github.com/builder-group/community/blob/develop/examples/openapi-router/express/petstore/src/router.ts Code: https://github.com/builder-group/community/blob/develop/packages/openapi-router/src/types/features/hono.ts
5 replies
HHono
Created by Benno on 7/9/2024 in #help
Enforce OpenAPI types
Hey there, I'm currently working on a openapi-router package, which aims to enforce types (generated from an OpenAPI document using openapi-typescript) in the routers of web frameworks like Hono or ExpressJs. I've successfully added support for ExpressJs, as its typings are relatively straightforward. However, I'm finding the Hono types more complex, and I could use some assistance in creating the appropriate Hono types for the openapi-router package. Is it even feasible to integrate Hono's advanced typing system with openapi-router? Any guidance or tips would be appreciated. Thanks 🙂 Context: - Hono Types: https://github.com/honojs/hono/blob/main/src/types.ts - Express types for openapi-router: https://github.com/inbeta-group/monorepo/blob/develop/packages/openapi-router/src/types/features/express.ts - Express example for openapi-router: https://github.com/inbeta-group/monorepo/tree/develop/examples/openapi-router/express/petstore
4 replies