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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:35:01