打字稿在具有继承的接口中使属性可选
Typescript make an attribute optionnal in an interface with inneritance
我的目标是克隆一个界面但更改一些参数。
我从我的数据库中得到了一个默认生成的界面,就像这样
interface Db {
id: number;
name: text;
...
}
界面很长,这就是为什么我不想复制所有这些(也是因为如果数据库模型发生变化,我不想手动更改我的第二个界面)。
因此,我的第二个接口应该与数据库接口完全相同,但 id 是可选的
我试过了:
interface NewInterface extends Db {
id ?: number;
}
但是 return 我出错了:id is need in ... but optionnal in ...
我也希望避免在我的代码中使用 delete 运算符。
但它不起作用,有人知道吗?
您可以这样定义您的新界面:
interface NewInterface extends Omit<Db, 'id'> {
id?: number;
}
我的目标是克隆一个界面但更改一些参数。 我从我的数据库中得到了一个默认生成的界面,就像这样
interface Db {
id: number;
name: text;
...
}
界面很长,这就是为什么我不想复制所有这些(也是因为如果数据库模型发生变化,我不想手动更改我的第二个界面)。
因此,我的第二个接口应该与数据库接口完全相同,但 id 是可选的
我试过了:
interface NewInterface extends Db {
id ?: number;
}
但是 return 我出错了:id is need in ... but optionnal in ...
我也希望避免在我的代码中使用 delete 运算符。 但它不起作用,有人知道吗?
您可以这样定义您的新界面:
interface NewInterface extends Omit<Db, 'id'> {
id?: number;
}