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

Prisma生成的TS类型无法检测不存在属性,如何解决?

解决Prisma生成TypeScript类型无法校验属性的问题

核心原因

Prisma默认导出的Recipe类型是泛型包装结构($Result.DefaultSelection<...>),用来适配不同查询的动态字段选择,因此不会直接暴露字面量类型,导致TypeScript无法对不存在的属性做校验。

解决方法

方法1:用Prisma.RecipeGetPayload生成具体类型

这是官方推荐的方式,通过指定查询参数生成对应实体类型。默认全选场景传入空对象即可:

import { Prisma } from '@prisma/client';

// 获取包含所有默认字段的Recipe类型
type RecipeFull = Prisma.RecipeGetPayload<{}>;

const RecipeCard = ({ recipe }: { recipe: RecipeFull }) => {
  // 此时访问recipe.fakeProperty会触发TypeScript错误
  const nonExistentProperty = recipe.fakeProperty;
  return <>></>;
};

如果需要指定特定字段,传入对应的select配置:

type RecipePartial = Prisma.RecipeGetPayload<{
  select: { id: true; title: true };
}>;
// 此时RecipePartial仅包含id和title属性

方法2:提取查询返回的类型

如果已有具体的Prisma查询逻辑,可以直接提取该查询的返回类型:

import { prisma } from '@/lib/prisma';

// 提取findFirst查询的返回类型
type RecipeFull = Awaited<ReturnType<typeof prisma.recipe.findFirst>>;

const RecipeCard = ({ recipe }: { recipe: RecipeFull }) => {
  // 同样会触发属性校验
  return <>></>;
};

方法3:检查版本与生成流程

  • 执行npm update prisma @prisma/client升级到最新稳定版,旧版本可能存在类型生成的兼容性问题。
  • 重新运行npx prisma generate,确保生成过程无报错,node_modules/.prisma/client下的类型文件正确生成。
  • 确认tsconfig.json中strict选项为true(你的配置已满足),这是TypeScript严格校验的前提。

内容的提问来源于stack exchange,提问作者Manuel Esperon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:13:14