Typescript 如何断言泛型类型T具有特定属性

Typescript 如何断言泛型类型T具有特定属性,typescript,abstract-class,Typescript,Abstract Class,我正在创建一个抽象类BaseRepository,它扩展了Repository。T被传递到这个抽象类中。方法main使用T的一部分,但是id应该是T的可选属性。如何断言T具有可选属性id export abstract class BaseRepository<T> extends Repository<T> { async main (changes: DeepPartial<T & { id?: number }>) { const p

我正在创建一个抽象类
BaseRepository
,它扩展了
Repository
。T被传递到这个抽象类中。方法
main
使用
T
的一部分,但是
id
应该是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 })
  }
}
导出抽象类BaseRepository扩展存储库{
异步主(更改:DeepPartial){
const p=this.create()
对象。分配(p,更改)
如果(p&p.id)等待此更新(p.id,p)
const v=等待这个。保存(p)
返回此.findOneOrFail({where:v})
}
}

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

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 })
  }
}
接口可识别{
id:编号;
}
导出抽象类BaseRepository扩展存储库{
异步主(更改:DeepPartial){
const p=this.create();
对象。分配(p,更改);
如果(p&p.id){
等待此更新(p.id,p);
}
const v=等待这个。保存(p);
返回此.findOneOrFail({where:v})
}
}

您可以执行类似于
BaseRepository
的操作,但这不起作用
this.update
的第二个参数是
T
,因此它抱怨它无法扩展E.
this.update()
与您提交的代码段没有更改。如果您在提交的代码段中看到错误(键入问题除外),在问题中包括这一点以及导致错误的任何方法,我会看看是否能提供帮助。