我有两个interfaces
,其中一个延伸到另一个.然而,我希望能够扩展第一个interface
并使其所有类型都可选.我不想把第一个interface
的所有定义都重写成第二个interface
的可选定义(因为在那一点上扩展有什么好处?)或者重新定义第一个interface
,因为它正在其他地方使用.
它看起来像什么:
interface First {
type1: string
type2: string
}
// Seemingly pointless rewrite (why would I even need to extend?)
interface Second extends First {
type1?: string
type2?: string
type3: string
type4: string
}
// What I imagine the extending should be (but doesn't work)
interface Second extends First? {
type3: string
type4: string
}
我做了研究,确实发现this question个答案非常相似,但自从这个问题被提及已经一年了,我认为我的问题并不完全相同,因为我想让entire扩展interface
可选,而不仅仅是其中的几个类型.
有没有办法在Typescript中做到这一点,或者我只需要吸收它,然后做一个长的interface
秒?
更新(解释我为什么想要这份工作):
我正在编写一个React web应用程序,其中有一个组件可以显示我数据库中的一个实体,允许用户编辑该实体的任何值.我希望我的React组件能够处理用户创建新实体的情况,以及用户编辑现有实体的情况.
为了与上面的示例保持一致,假设我的数据库实体的值由First interface
复制,React组件使用Second interface
中存在的两个传递的props .react 组分always将具有Second中的两个值,但不一定具有First的值.
在用户创建一个新实体的情况下,我希望只使用Second的值来构造React组件,而不必为First中的所有内容指定null
个值.在用户编辑现有实体的情况下,我将传递First和Second中的所有内容.
在这两种情况下,它都是相同的UI,但使用不同的值集构建.