简体   繁体   English

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

[英]How can I assert that generic type T has specific property

I am creating an abstract class BaseRepository which extends Repository .我正在创建一个扩展Repository的抽象 class BaseRepository T is passed into this abstract class. T 被传递到这个抽象 class 中。 The method main takes a partial of T but id should be an optional prop of T. How can I assert T to have optional prop id ?方法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 })
  }
}

Asserting that the generic type has an optional property is pretty simple.断言泛型类型具有可选属性非常简单。 Just define an interface that has the property and say that the type extends that interface.只需定义一个具有该属性的接口,并说该类型扩展了该接口。 This would look something like这看起来像

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 })
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM