0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Hono RPCでclientがunknownになる罠(Cloudflare Workers + TypeScript)

0
Posted at

Hono のRPCを公式どおりに書いているのに、VS Codeで clientunknown になってハマったので、原因と解決をまとめます。
結論だけ先に言うと、RPCの書き方ではなく今回はtsconfig.jsonのlib設定が原因でした。

症状

Cloudflare Workers テンプレートで作ったプロジェクトで、以下のように書いていました。

// server
const route = app
    .get("/posts", ...)
    .post("/posts", ...)
    .get("/posts/:id", ...)

export type AppType = typeof route
  // client
import { hc } from "hono/client"
import type { AppType } from "./app"

const client = hc<AppType>("http://localhost:8787/")
client.posts.$get()

にもかかわらず、VS Code で:

  • client is of type 'unknown'. ts(18046)
  • 補完が出たり出なかったりして不安定

先に結論

原因は tsconfig.json がこうなっていたことです。

  "lib": ["ESNext"]

Cloudflare Workers + Hono RPC では、

  • fetch
  • Request
  • Response

などの Web API型 が必要です。

しかし lib: ["ESNext"] だけだと、これらの型が含まれていません。

その結果:

  • Hono内部の型解決が崩れる
  • RPCの型推論が壊れる
  • hc() の戻り値が unknown になる

という状態になります。

正しい設定(Workers向け)

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "skipLibCheck": true,
    "lib": ["ESNext", "WebWorker"],
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}

DOM でも通りますが、Cloudflare Workersの場合は WebWorker の方が適切です。

なぜ気づきにくいのか

skipLibCheck: true だと、依存パッケージ内部の型エラーが抑制されます。
その結果、根本原因が見えず、最終的に client: unknown だけが症状として出ることがあります。

追加でやっておくと安定すること

1.typescript を明示的に入れる

npm i -D typescript

2.型チェック用スクリプトを追加

{
  "scripts": {
    "typecheck": "tsc --noEmit"
  }
}

3.VS CodeでワークスペースTSを使う

  • TypeScript: Select TypeScript Version → Use Workspace Version
  • TypeScript: Restart TS Server

最小の構成メモ(おすすめ)

  • src/app.ts に app と AppType を置く
  • src/index.tsexport default app のみ
  • client.tsimport type { AppType } from "./app"

これで型の伝播が安定しやすいです。

まとめ

Cloudflare Workers 環境で Hono RPC を使う場合、
libWebWorker を入れるのを忘れると型推論が壊れるので注意です。

参考になったら幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?