Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何在TypeForm中为实体类型添加约束?_Typescript_Typeorm - Fatal编程技术网

Typescript 如何在TypeForm中为实体类型添加约束?

Typescript 如何在TypeForm中为实体类型添加约束?,typescript,typeorm,Typescript,Typeorm,我正在尝试创建一个接口,并让我的一些实体实现它,这样我就可以对它们进行概括,但我似乎无法正确地实现它 假设我有一些实体类型,我想在其中一些类型中添加一个函数全名 @Entity() class User { @Column() firstName!: string; @Column() lastName!: string; fullName(): string { return `${this.firstName} ${this.lastName}`; } }

我正在尝试创建一个接口,并让我的一些实体实现它,这样我就可以对它们进行概括,但我似乎无法正确地实现它

假设我有一些
实体
类型,我想在其中一些类型中添加一个函数
全名

@Entity()
class User {
  @Column()
  firstName!: string;

  @Column()
  lastName!: string;

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

@Entity()
class Dog {
  // doesn't have fullName
}

interface HasFullName {
  fullName: () => string;
}
我想要一个函数,它接受一个实现了
HasFullName
的实体,并对其进行处理,因此我继续编写这样一个函数

function getFullName(
  connection: Connection,
  model: EntityTarget<HasFullName>,
): Promise<string[]> {
  return connection
    .getRepository(model)
    .createQueryBuilder()
    .getMany()
    .then((xs) => xs.map((x) => x.fullName()));
}
getFullName(connection, User)
但事实证明,我也可以用
Dog
调用它,尽管它没有实现
HasFullName
接口

getFullName(connection, Dog) // It compiles!?
我必须想出这样的方法,在这里我必须显式地传递类型参数以使其工作

function getFullName<T extends HasFullName>(
  connection: Connection,
  model: EntityTarget<T>,
): Promise<string[]> {
  ...
}

// and call it like this
getFullName<User>(connection, User)

getFullName<Dog>(connection, Dog) // Doesn't compile
getFullName<User>(connection, Dog)
const a: EntityTarget<boolean> = User;