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

使用Prisma ORM构建API时遇动态模型索引TypeScript类型错误

解决Prisma父类动态模型调用的TypeScript类型错误

问题核心

TypeScript报错的原因是model变量的类型被宽泛定义为string,但PrismaClient仅允许使用自身生成的模型名称作为索引,因此需要严格约束model的类型范围。

解决方案代码

调整Repository类的实现,通过类型约束和泛型让TypeScript正确识别模型类型:

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

// 提取PrismaClient的所有合法模型名称类型
type PrismaModelName = keyof PrismaClient;
// 自动推导对应模型的实体类型
type PrismaModel<T extends PrismaModelName> = PrismaClient[T] extends { findMany: () => Promise<infer U> } ? U : never;

export default class Repository<T extends PrismaModelName> {
  public model: T;
  private prisma = new PrismaClient();

  constructor(model: T) {
    this.model = model;
  }

  public async getAll(): Promise<PrismaModel<T>> {
    // TypeScript现在能精准推断模型方法的类型
    const result = await this.prisma[this.model].findMany();
    return result;
  }
}

子类使用示例

假设你有user模型,子类继承时只需指定模型名称即可复用父类逻辑:

class UserRepository extends Repository<'user'> {
  constructor() {
    super('user');
  }

  // 添加子类专属方法
  public async getByEmail(email: string) {
    return this.prisma.user.findUnique({
      where: { email }
    });
  }
}

关键优化点

  • 用keyof PrismaClient限定模型名称的合法范围,消除隐式any类型
  • 通过泛型T和PrismaModel<T>让返回类型精准对应模型实体,替代模糊的Object
  • 构造函数传入模型名称,避免父类硬编码模型名,提升复用性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:03