Keystone问题:如何基于已定义列表获取上下文类型?
解决KeystoneContext类型不匹配问题
错误原因
你传入KeystoneContext的泛型参数结构不符合要求——BaseKeystoneTypeInfo约束要求lists属性是**列表的类型信息(BaseListTypeInfo)**集合,但你传入的是ListConfig(列表配置对象),两者结构不兼容,因此出现类型缺失的报错。
修正方案
方案1:使用Keystone自动生成的TypeInfo
Keystone会在项目的.keystone/types.ts文件中自动生成TypeInfo类型,直接导入使用即可:
// 导入自动生成的TypeInfo import type { TypeInfo } from './.keystone/types'; import { getContext } from '@keystone-6/core'; import config from './keystone'; import PrismaModule from '.prisma/client'; export const keystoneContext = ((globalThis as any).keystoneContext || getContext(config, PrismaModule)) as KeystoneContext<TypeInfo>;
方案2:手动构建正确的TypeInfo类型
如果无法使用自动生成的类型,需要从你的lists配置中提取每个列表的typeInfo(而非直接用typeof lists):
import type { KeystoneContext, BaseKeystoneTypeInfo } from '@keystone-6/core/types'; import { getContext } from '@keystone-6/core'; import config from './keystone'; import PrismaModule from '.prisma/client'; import lists from './lists'; // 提取每个列表的TypeInfo类型 type ListTypeInfos = { [K in keyof typeof lists]: (typeof lists[K])['typeInfo']; }; // 构建符合BaseKeystoneTypeInfo要求的类型 type CustomKeystoneTypeInfo = BaseKeystoneTypeInfo & { lists: ListTypeInfos; prisma: typeof PrismaModule.PrismaClient; session: any; }; export const keystoneContext = ((globalThis as any).keystoneContext || getContext(config, PrismaModule)) as KeystoneContext<CustomKeystoneTypeInfo>;
验证修正
修正后,context.query.User(或其他列表)应该能获得完整的类型提示,包括查询方法、返回字段的类型支持。
内容的提问来源于stack exchange,提问作者Shreyas Jadhav
相关产品推荐
相关产品推荐

