【问题标题】:Typescript make an attribute optionnal in an interface with inneritance打字稿在具有继承的接口中使属性可选
【发布时间】:2021-08-13 10:53:02
【问题描述】:

我的目标是克隆一个界面但更改一些参数。 我从我的数据库中得到了一个默认生成的界面,就像这样

interface Db {
  id: number;
  name: text;
  ...
}

界面很长,这就是我不想复制所有内容的原因(也因为如果数据库模型更改,我不想手动更改我的第二个界面)。

所以,我的第二个接口应该与数据库完全相同,但 id 为可选

我试过了:

interface NewInterface extends Db {
  id ?: number;
}

但它返回一个错误:id is need in ... but optionnal in ...

我还希望避免在我的代码中使用删除运算符。 但它不起作用,有人知道吗?

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:

    你可以这样定义你的 NewInterface:

    interface NewInterface extends Omit<Db, 'id'> {
        id?: number; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2016-10-05
      • 2019-12-02
      • 2021-07-26
      • 2017-12-04
      相关资源
      最近更新 更多