【问题标题】:Interface/type with a removed property具有已移除属性的接口/类型
【发布时间】:2019-12-06 06:10:07
【问题描述】:

我尝试创建许多不同的interfaces 和types,以不同的方式组合联合和交集,但都失败了。

我有一个带有一些属性的接口:

interface A {
    name: string;
    property: number;
    // many many more...
}

我想创建一个基于 A 的新接口(或类型,我现在不关心),其中删除了 name 并添加了一些其他属性,结果是:

interface B {
    property: number;
    age: number;
    // everything else that A had, except name
}

我将如何使用 TypeScript 的交集/联合或其他可能性来做到这一点?

我什至尝试在A 和另一个接口之间创建一个交集name?: never; 以摆脱该字段,但是我该如何添加其他属性?

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:

    使用Omit<A, 'name'>&{other properties}

    【讨论】:

      【解决方案2】:
      interface A {
          name: string;
          property: number;
          foo: string;
      }
      
      // Get rid of name property
      type AWithoutName = Omit<A, "name">;
      
      // Now use the type to get all of A without name
      const foo: AWithoutName = { property: 2, foo: "hello" }
      
      // extend this type to add more props without name
      interface AddMoreToA extends AWithoutName {
        bar: string;
      }
      
      // use in this way
      const bar: AddMoreToA = { property: 2, foo: "hello", bar: "world" }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 1970-01-01
        • 2018-09-01
        • 2020-01-01
        • 2022-10-15
        相关资源
        最近更新 更多