typeorm和nestjs中的泛型类型

问题描述 投票:0回答:1

我正在尝试创建一个可扩展的基本服务。该服务采用泛型类型,它将是typeorm使用的实体类型,该类型必须具有一些道具,因此我希望它扩展具有这些道具的接口:

import { getManager, FindConditions, Repository } from "typeorm";
import { UserInterface } from "./user.interface";

export abstract class UserService<User extends UserInterface> {
  constructor(
    private readonly User: new () => User,
    protected readonly userRepository: Repository<User>,
  ) {}

  async findAll(): Promise<User[]> {
    return await this.userRepository.find();
  }

  abstract async findOnePopulated(where: FindConditions<User>): Promise<User>;

  async findOneById(id: number): Promise<User> {
    return await this.findOnePopulated({ id });
  }

  async updateUser(userId: number): Promise<User> {
    const em = getManager();
    const user = await this.userRepository.findOne(userId);

    await em.update(this.User, userId, user);
    return user;
  }
}

我在这次调用findOnePopulated({ id })时遇到类型错误

[ts] Argument of type '{ id: number; }' is not assignable to parameter of type
'FindConditions<User>'. [2345]

而这个em.update(this.User, userId, user)也显示了一个类型错误:

[ts]
Argument of type 'User' is not assignable to parameter of type 'QueryDeepPartialEntity<User>'.
  Type 'UserInterface' is not assignable to type 'QueryDeepPartialEntity<User>'. [2345]

如果我将所有User切换到UserInterface,似乎没有显示任何错误,是否使用语法<User extends UserInterface>有问题?

我只想确保通用用户类型至少具有UserInterface中的道具。

这是我的用户界面:

import { BaseEntity } from "typeorm";

export interface UserInterface extends BaseEntity {
  id: number;
}
typescript nestjs typeorm
1个回答
0
投票

我花了一段时间来解决它,但我猜你的UserInterface是造成这些问题的原因。你没有一个名为User的实体吗? UserInterfaceid型的关键number吗?你有没有宣称UserInterfaceEntity?如果你能提供你的UserInterface,我会再看看,但我的猜测是因为它不是一个实体@Entity()因此没有在typeorm的实体经理等注册

© www.soinside.com 2019 - 2024. All rights reserved.