首页 > 解决方案 > 我如何断言泛型类型 T 具有特定属性

问题描述

我正在创建一个BaseRepository扩展的抽象类Repository。T 被传递到这个抽象类中。该方法main采用 T 的一部分,Tid应该是 T 的可选属性。我如何断言 T 具有可选属性id

export abstract class BaseRepository<T> extends Repository<T> {
  async main (changes: DeepPartial<T & { id?: number }>) {
    const p = this.create()
    Object.assign(p, changes)
    if (p && p.id) await this.update(p.id, p )
    const v = await this.save(p)
    return this.findOneOrFail({ where: v })
  }
}

标签: typescriptabstract-class

解决方案


断言泛型类型具有可选属性非常简单。只需定义一个具有该属性的接口,并说该类型扩展了该接口。这看起来像

interface Identifiable {
  id: number;
}

export abstract class BaseRepository<T extends Identifiable> extends Repository<T> {
  async main (changes: DeepPartial<T>) {
    const p = this.create();
    Object.assign(p, changes);

    if (p && p.id) {
      await this.update(p.id, p);
    }

    const v = await this.save(p);
    return this.findOneOrFail({ where: v })
  }
}

推荐阅读