typescript - 我如何断言泛型类型 T 具有特定属性
问题描述
我正在创建一个BaseRepository
扩展的抽象类Repository
。T 被传递到这个抽象类中。该方法main
采用 T 的一部分,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 })
}
}
解决方案
断言泛型类型具有可选属性非常简单。只需定义一个具有该属性的接口,并说该类型扩展了该接口。这看起来像
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 })
}
}
推荐阅读
- php - 增量 (+1) Php/MongoDB - MongoDB\Driver\Manager 的 FindOneAndUpdate
- c# - 使用 Webmatrix、Bootstrap、Html 和 SQL 为 ForeignKey 保留相同 ID 的两个表插入
- python - 我无法用字典解决的python IndexError
- .net - AWS CodeBuild 中是否支持 GitVersion?
- python - xgboost 特征重要性类型“增益”是否与 MDI 相同?
- html - 在 HTML 表格中显示上下文变量
- python - 发送带有请求和美味派的 json 文件
- ios - SwiftUI - 如何将文本视图与另一个文本视图垂直对齐,以制作类似于正确对齐的表格?
- javascript - 这部分代码没有激活,{ document.getElementsByClassName("info")[0].innerText = "Turn for " + turn; } 不能显示玩家回合
- shopify - 如何在 integromat 上找到有关 shopify 废弃结账的详细信息?