【发布时间】:2017-10-21 10:37:11
【问题描述】:
我有两个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 回答了非常相似的问题,但是自从这个问题被触及以来已经有一年了,我认为我的问题并不完全相同,因为我想让整个 扩展interface 可选,不只是其中的几个类型。
有没有什么办法可以在 Typescript 中做到这一点,还是我只需要把它吸起来然后花很长的时间interface?
更新(解释我为什么想要这项工作):
我正在编写一个 React Web 应用程序,并且有一个组件可以显示我的数据库中的一个实体,这种方式允许用户编辑该实体的任何值。我希望我的 React 组件能够处理用户正在创建新实体的情况,以及用户正在编辑现有实体的情况。
为了与上面的示例保持一致,假设我的数据库实体的值由 First interface 复制,并且 React 组件使用存在于 Second 中的两个传递的道具强>interface。 React 组件将始终在 Second 中具有两个值,但不一定具有 First 中的值。
在用户创建新实体的情况下,我想只使用 Second 的值来构造 React 组件,而不必为 中的所有内容指定 null 值>首先。在用户编辑现有实体的情况下,我会传递 First 和 Second 的所有内容。
在这两种情况下,它都是相同的 UI,但使用一组不同的值构造。
【问题讨论】:
-
你的情况是什么。更新帖子将帮助您
标签: javascript typescript interface