You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite React中Bun RPC+Hono出现client类型unknown(TS18046)错误

解决Hono客户端类型错误:'client' is of type 'unknown'

问题概述

在Vite React应用中使用Bun RPC + Hono框架时,调用client.api.user.$get()出现TypeScript错误'client' is of type 'unknown'.ts(18046),仅直接挂载的根路由能被识别,嵌套route()挂载的子路由类型无法推导。


解决方案

1. 服务端调整类型导出逻辑

使用Hono内置的InferRouterType工具类型,正确提取包含嵌套路由的完整类型信息,替代直接使用typeof获取实例类型。

修改server/app.ts:

import { Hono } from 'hono'
import type { InferRouterType } from 'hono'
import userRoutes from './userRoutes' // 替换为你的userRoutes实际路径

export const app = new Hono()
  .basePath('/api')
  .route('/user', userRoutes)

// 导出经过类型提取的路由结构
export type AppType = InferRouterType<typeof app>

2. 确认子路由的类型正确性

确保userRoutes是标准的Hono实例,示例如下:

// server/userRoutes.ts
import { Hono } from 'hono'

const userRoutes = new Hono()
  .get('/', (c) => c.json({ data: 'User list' }))
  .get('/:id', (c) => c.json({ id: c.req.param('id') }))

export default userRoutes

3. 客户端代码无需修改

保持原客户端代码不变,此时client.api.user.$get()的类型会被正确识别:

import { useEffect } from "react"
import { hc } from "hono/client"
import { type AppType } from "../../server/app"

const client = hc<AppType>("/");

function App() {
    useEffect(() => {
        const fetchTotal = async () => {
            const resp = await client.api.user.$get()
            // 后续逻辑
        }
        fetchTotal()
    }, [])

    return (
        // 组件内容
    )
}

export default App

问题原因分析

直接使用typeof appRoute获取的是Hono实例的基础类型,无法正确解析嵌套route()挂载的子路由结构。而InferRouterType是Hono专门为路由类型推导设计的工具,能完整提取所有路由的路径、方法和响应类型,让hc函数生成带有完整类型提示的客户端实例。

当你在basePath后直接添加.get("/")时,根路由的类型被直接包含在实例类型中,因此client.api.$get()能被识别,但嵌套子路由的类型信息未被正确提取,导致client.api.user无法被TypeScript识别。


额外检查项

  • 确保服务端与客户端的Hono版本完全一致,版本不匹配可能引发类型推导异常。
  • 确认tsconfig.json配置:compilerOptions.strict: true,同时compilerOptions.moduleResolution设为bundler,compilerOptions.esModuleInterop: true,这些配置能帮助TypeScript正确处理Hono的类型模块。

内容的提问来源于stack exchange,提问作者owdx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 23:58:19