javascript - typescript 可选扩展接口(interface)

标签 javascript typescript interface

我有两个接口(interface),其中一个扩展了另一个。但是,我希望能够扩展第一个 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 网络应用程序,并且有一个组件显示我的数据库中的一个实体,允许用户编辑该实体的任何值。我希望我的 React 组件能够处理用户创建新实体的情况,以及用户编辑现有实体的情况。

为了与我上面的示例保持一致,假设我的数据库实体的值由 First interface 复制,并且 React 组件使用存在于 < strong>第二个 接口(interface)。 React 组件将始终Second 中具有两个值,但不一定具有First 中的值。

在用户创建新实体的情况下,我想只使用 Second 的值构建 React 组件,而不必指定 null 值对于 First 中的所有内容。在用户编辑现有实体的情况下,我会传递 FirstSecond 中的所有内容。

在这两种情况下,它都是相同的 UI,但使用不同的值集构建。

最佳答案

您可以使用 type aliases连同 intersectionPartial 上输入:

type First = {
    type1: string;
    type2: string;
}

type Second = Partial<First> & {
    type3: string;
    type4: string;
}

关于javascript - typescript 可选扩展接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101534/

相关文章:

javascript - 使用 sinon、mocha 和 SWC 对导出函数进行 stub 失败

angular - 如何使特定单元格在 primeNG 的内联可编辑行中不可编辑

typescript - 扩展抽象类的类的类型是什么?

javascript - 在 setInterval 中捕获异常

javascript - 尝试使用箭头语法重写它

performance - Javascript、IE、字符串和性能问题

接口(interface)中的 Java 静态方法/字段(再次!)

javascript - 将 'n' 项添加到本地存储(项从 json 文件获取)

Java 枚举在接口(interface)或类中的放置

java - 具有反向关系的通用接口(interface)