Since v4.10.0, we always have to branch by status or ok to get the correct types in RPC (hc).
#4575
Unanswered
baseballyama
asked this question in
Q&A
Replies: 1 comment 2 replies
-
|
@baseballyama this is the expected consequence of PR #4393 (v4.10.0). the route schema now includes middleware error responses via you don't actually need to branch by import type { InferResponseType } from 'hono/client'
// extracts only the 200 response type
type SuccessData = InferResponseType<typeof client.api.users.$get, 200>or if you have a centralized fetch wrapper, type it to narrow automatically: import type { InferResponseType, ClientResponse } from 'hono/client'
import type { SuccessStatusCode } from 'hono/utils/http-status'
async function fetchApi<T extends (...args: any[]) => Promise<ClientResponse<any, any, any>>>(
fn: T, ...args: Parameters<T>
): Promise<InferResponseType<T, SuccessStatusCode>> {
const res = await fn(...args)
if (!res.ok) throw new Error(`API error: ${res.status}`)
return await res.json() as InferResponseType<T, SuccessStatusCode>
}the |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
PR #4393 improved the ability to get accurate types for specific status codes. While this is a great improvement on its own, it is causing an issue in my project.
In my project, we centrally manage 4xx and 5xx errors using a customized fetch function. Our design allows individual UI components to handle only the success cases. Previously, this meant our UI components were type-safe without needing to explicitly check the response code.
However, since v4.10.0 (where #4393 was released), we can no longer resolve the types without checking status or ok in each UI component. As a result, we are forced to add these checks to every single API call site. This negatively affects the codebase by reducing readability (due to increased boilerplate) and increasing the bundle size.
Is there a way to maintain type safety without manually checking status or code, just as we were able to do before? Any advice would be appreciated.
Beta Was this translation helpful? Give feedback.
All reactions