打字稿可选扩展接口

新手上路,请多包涵

我有两个 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
}

我做了我的研究,确实发现 这个问题 回答了一些非常相似的问题,但是自从触及这个问题已经一年了,我认为我的问题并不完全相同,因为我想使 整个 扩展 interface 可选的,不仅仅是它的几种类型。

有什么方法可以在 Typescript 中执行此操作,还是我只需要吸收它并花很长时间 interface


更新(解释为什么我想要这项工作):

我正在编写一个 React Web 应用程序,并且有一个组件显示我的数据库中的一个实体,允许用户编辑该实体的任何值。我希望我的 React 组件能够处理用户正在创建新实体的情况,以及用户正在编辑现有实体的情况。

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

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

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

原文由 Louie Bertoncin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 253
2 个回答

您可以在 Partial 类型上使用 类型别名交集

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

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

原文由 Nitzan Tomer 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 Partial 类型的接口执行此操作。

 interface First {
    type1: string;
    type2: string;
}

interface Second extends Partial<First> {
    type3: string;
    type4: string;
}

原文由 Dibyo Majumdar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题