网站搜索

next.js - TypeScript 推断类型错误 - 作为别名导入并默认为 any


我正在使用 Nextjs 构建一个前端 monorepo,同时使用 bun 和 hono 构建后端。我正在尝试使用 hono rpc:https://hono.dev/docs/guides/rpc。我在后端项目的 app.ts 文件中这样导出我的路由器类型:

import createApp from '@/lib/create-app'
import configureOpenAPI from '@/lib/configure-open-api'
import index from '@/routes/index.route'
import users from '@/routes/user/user.index'
import connects from '@/routes/connects/connects.index'

const app = createApp()

const routes = [index, users, connects] as const

configureOpenAPI(app)

routes.forEach((route) => {
  app.route('/', route)
})

export default app

export type AppType = (typeof routes)[number]

然后尝试在我的前端项目的 client.ts 文件中导入它

import type { AppType } from '../backend/src/app'
import { hc } from 'hono/client'

const client = hc<AppType>('http://localhost:8000')

export default client

这不起作用,而且我的类型被推断为 any。当我在后端的 app.ts 中悬停在 app 类型上时,我看到这个类型

type AppType = OpenAPIHono<AppBindings, {
    "/": {
        $get: {
            input: {};
            output: {
                message: string;
            };
            outputFormat: "json" | "text";
            status: 200;
        };
    };
}, "/"> | OpenAPIHono<AppBindings, {
    ...;
}, "/"> | OpenAPIHono<...>

它100%有正确的类型。

然而,当我在 client.ts 中将鼠标悬停在 AppType 上时,我看到这个:

(alias) type AppType = any
import AppType

我该如何解决这个问题:

自己查看的仓库 + 所有 tsconfigs: https://github.com/charlietlamb/postpad

谢谢你的帮助!

答案#1

终于回答了这个——需要添加

"references": [
        { "path": "../backend/tsconfig.json" }
    ],

到我的后端和

"composite" : true

在我的前端

https://www.youtube.com/watch?v=S-jj_tifHl4

答案#2

当在 TypeScript 中使用路径(@ 快捷方式)时会发生这种情况。

前端(AppType 被导入的地方):添加 "references": [{ "path": "../back" }](back 是包含导出 AppType 的后端的文件夹名称)。

turborepo/apps/front/tsconfig.app.json(对你来说可能是 tsconfig.json)

{
  "compilerOptions": {
    "target": "ES2020",
     ...
     "paths": {
       "@/*": ["./src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "../back" }]
}

后端(定义并导出 AppType 的地方)tsconfig.json:在编译器选项中添加 "composite": true

turborepo/apps/back/tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    ...
    "paths": {
      "@/*": ["./src/*"]
    },
    "composite": true
  }
}

更多信息请见:

https://github.com/honojs/hono/issues/3109 https://github.com/honojs/hono/issues/3109#issuecomment-2222892161

https://www.typescriptlang.org/docs/handbook/project-references.html