TypeORM find返回类型与定义的Student实体类型不匹配问题求助
TypeScript 泛型误用导致的类型不匹配问题
问题代码
import { Student } from "core" import { Repository } from "./Repository" import { Database } from "../../db" export class UserRepository<Student> extends Repository<Student> { private _repository = Database.AppDataSource.getRepository(Student); public override async GetById (id: number): Promise<Student | null> { return await this._repository.findOneBy({ id: id }); } public override async ListAll (): Promise<Student[]> { return await this._repository.find(); } }
说明:
Student类型定义在core模块中
构建错误信息
Data/Repositories/StudentRepository.ts:7:9 - error TS2322: Type 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student | null' is not assignable to type 'Student | null'. Type 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student' is not assignable to type 'Student'. 'Student' could be instantiated with an arbitrary type which could be unrelated to 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student'. 7 return await this._repository.findOneBy({ id: id }); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data/Repositories/StudentRepository.ts:10:9 - error TS2322: Type 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student[]' is not assignable to type 'Student[]'. Type 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student' is not assignable to type 'Student'. 'Student' could be instantiated with an arbitrary type which could be unrelated to 'import("/usr/src/Node.JSRestAPI/src/core/build/index").Student'. 10 return await this._repository.find(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
错误原因
你在定义 UserRepository 时,把 Student 声明成了泛型参数,这会覆盖从 core 模块导入的 Student 类型。此时类中的 Student 不再是你导入的具体类型,而是一个可被任意类型替换的泛型占位符,导致 TypeScript 无法识别它与数据库返回的 Student 类型一致,从而抛出类型不匹配错误。
解决方案
移除类定义中的泛型参数 <Student>,直接使用从 core 模块导入的 Student 类型:
import { Student } from "core" import { Repository } from "./Repository" import { Database } from "../../db" // 移除泛型参数 <Student>,直接为基类 Repository 指定具体类型 Student export class UserRepository extends Repository<Student> { private _repository = Database.AppDataSource.getRepository(Student); public override async GetById (id: number): Promise<Student | null> { return await this._repository.findOneBy({ id: id }); } public override async ListAll (): Promise<Student[]> { return await this._repository.find(); } }
如果 Repository 基类本身是泛型类,只需在继承时传入导入的 Student 类型即可,无需将 Student 重新声明为当前类的泛型参数。
内容的提问来源于stack exchange,提问作者khteh
相关产品推荐
相关产品推荐

