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

TypeScript中IResolvers类型无法赋值给ServerOptions的resolvers属性问题求助

TypeScript中IResolvers类型无法赋值给ServerOptions的resolvers属性问题求助

我现在遇到一个TypeScript类型兼容的问题,折腾了好久没搞明白,想请大家帮忙看看。

首先说下我的场景:
我在一个独立的monorepo里定义了这样的类型:

import {IExecutableSchemaDefinition} from "@graphql-tools/schema"

export type ServerOptions<TContext> = {
    // 这个类型对应@graphql-tools/utils里的‘IResolvers<any, MyContext> | Array<IResolvers<any, MyContext>> | undefined’
    resolvers: IExecutableSchemaDefinition<TContext>["resolvers"]
    // 其他无关类型省略
}

然后在另一个项目里,我这么使用:

import {IResolvers} from "@graphql-tools/utils"
import {mergeResolvers} from "@graphql-tools/merge"
import {ServerOptions} from "my-package"

const mergedResolvers: IResolvers<any, MyContext> = mergeResolvers(myResolversList)

const serverOptions: ServerOptions<MyContext> = {
    resolvers: mergedResolvers
}

结果在serverOptions的resolvers属性下面出现了TypeScript错误:

Type 'IResolvers<any, MyContext>' is not assignable to type 'IResolvers<any, MyContext> | IResolvers<any, MyContext>[] | undefined'.
Type 'IResolvers<any, MyContext>' is missing the following properties from type 'IResolvers<any, MyContext>[]': length, pop, push, concat, and 35 more.ts(2322)
ServerOptions.d.ts(10, 5): The expected type comes from property 'resolvers' which is declared here on type 'ServerOptions'

我完全搞不懂为啥会报错啊——mergedResolvers的类型明明就是联合类型里的第一个选项啊!

现在我只能用类型断言来绕过去,代码是这样的:

const mergedResolvers: ServerOptions<MyContext>['resolvers'] = 
    mergeResolvers(myResolversList) as ServerOptions<MyContext>['resolvers']

但我想搞明白底层的问题到底出在哪。我也仔细排查了类型定义的来源:

  • 我当前项目里直接引入的IResolvers,路径是node_modules > @graphql-tools > utils > typings > interfaces.d.ts
  • 而ServerOptions里的resolvers类型,溯源路径是:
    • 首先ServerOptions定义在user > dev > my-monorepo > packages > my-package > dist > types > src > common > types > ServerOptions.d.ts
    • 它依赖的IExecutableSchemaDefinition在user > dev > my-monorepo > node_modules > .pnpm > @graphql-tools+schema@10.0.30_graphql@16.12.0 > node_modules > @graphql-tools > schema > typings > types.d.ts
    • 最终关联到的IResolvers在user > dev > my-monorepo > node_modules > .pnpm > @graphql-tools+utils@10.11.0_graphql@16.12.0 > node_modules > @graphql-tools > utils > typings > interfaces.d.ts

而且我对比了这两个IResolvers的类型定义,内容是完全一样的,没有区别。

有没有大佬能解释下这个问题到底是怎么回事呀?


备注:内容来源于stack exchange,提问作者Gabi23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 18:04:38