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

如何修复实现IUsersRepository接口后无法获取值的问题?

修复UsersRepository实现IUsersRepository接口的问题

我用UsersRepository类实现了IUsersRepository接口,但无法从该接口获取对应值,相关代码如下:

实现IUsersRepository接口的UsersRepository类

import { getRepository, Repository } from "typeorm"; 
import { IUsersRepository } from "../IUsersRepository"; 
import { User } from "../../entities/User";
import { ICreateUserDTO } from "../../../../dtos/usersDto";

class UsersRepository implements IUsersRepository {

    private repository: Repository<User>;
    
    constructor() {
        this.repository = getRepository(User);
    }

    async create({ name, email, password, age }: ICreateUserDto): Promise<void> {
        const user = this.repository.create({
            name,
            email, 
            password,
            age
        }); 
        await this.repository.save(user);
    }

    async findBy Email(email: string): Promise<User> {
        const user = this.repository.findByEmail({ email }); 
        return user;
    }

    async findById(id: string): Promise<User> {
        const user = this.repository.findById(id); 
        return user;
    }
    
export { Users Repository }

IUsersRepository接口定义

import { ICreateUserDTO } from "../../../dtos/usersDto", 
import { User } from "../entities/User";

interface IUsersRepository {
    create(data: ICreateUserDTO): Promise<void>; 
    findByEmail(email: string): Promise<User>; 
    findById(id: string): Promise<User>;
}

export { IUsersRepository }

修复步骤

  • 修正方法名与导出的拼写错误:
    • 将findBy Email中间的空格删除,改为findByEmail,与接口定义的方法名保持一致;
    • 导出语句里的Users Repository空格删除,改为UsersRepository,避免导出无效的类。
  • 统一类型定义的大小写:
    • create方法的参数类型ICreateUserDto改为ICreateUserDTO,和接口及导入的类型保持一致。
  • 修正TypeORM Repository的方法调用:
    • TypeORM的Repository类没有内置findByEmail和findById方法,需用findOne替代,同时要加await处理异步操作:
      async findByEmail(email: string): Promise<User | null> {
          return await this.repository.findOne({ where: { email } });
      }
      
      async findById(id: string): Promise<User | null> {
          return await this.repository.findOne({ where: { id } });
      }
      
    • 提示:findOne可能返回null,建议将方法返回类型调整为Promise<User | null>,适配实际返回值。
  • 修正接口文件的语法错误:
    • 接口定义中import语句结尾的逗号改为分号:
      import { ICreateUserDTO } from "../../../dtos/usersDto";
      import { User } from "../entities/User";
      

内容的提问来源于stack exchange,提问作者Patrick Borges Martins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:57:21