【发布时间】:2020-04-17 23:11:45
【问题描述】:
我有以下 TypeScript 接口,用作 ORM 库的数据库实体:
export interface Entity {
id?: number;
someColumn: string;
someOtherValue: number;
otherColumn: string;
}
注意可选的id 属性,它可以是实体的主键,也可以是未定义的。
如果未定义,则表示该实体在底层数据库中不存在。
但是,许多函数只接受具有有效 id 的 Entity-objects。
因此,我想介绍一个看起来像这样的新界面(没有“?”):
export interface ValidEntity {
id: number;
someColumn: string;
someOtherValue: number;
otherColumn: string;
}
现在我的问题是我不想复制原始Entity-interface 中的所有属性。
如何使用约束“扩展”Entity-interface 以强制 id 不得未定义?
反转问题
另一个问题是相反方向的同一件事。
假设我们已经有了ValidEntity 接口,并且想要创建一个Entity 接口来放宽id 属性以允许未定义。我们如何在不复制属性的情况下实现这种放松?
【问题讨论】:
标签: typescript