如何在继承接口时向对象添加属性



总结我的问题,我有一个接口,User,带有一个充满属性的'属性'对象。我有另一个界面 SpecialUser,其中"属性"对象需要包含用户上不存在的属性。目前,新属性对象正在覆盖旧属性对象。我可以通过粘贴父界面中的所有属性然后附加后面的属性来使其工作,但这不是最理想的解决方案。

export interface User{
attributes: {
full_name: string;
}
}
export interface SpecialUser extends User {
attributes: {
occupation: string;
}
}

我想要的是让 SpecialUser 的"属性"除了包含其新属性之外的用户"属性"上的字段(因此它将同时包含full_name和职业(。实际结果是完全覆盖。

一种选择是使用交集类型。

interface User {
attributes: {
full_name: string;
};
}
type SpecialUser = {
attributes: {
occupation: string;
};
} & User;
const user: SpecialUser = {
attributes: {
occupation: "job",
full_name: "name"
}
};

打字稿游乐场

这样的东西适合你的用例吗?

export interface User{
attributes: {
full_name?: string;
occupation?: string;
}
}

或者因为你真的在修改属性

export interface Attributes{
full_name: string;
}
export interface SpecialAttributes extends Attributes {
//has all other properties of original attributes (i.e. full_name)
occupation: string;
}
export interface User{
attributes: Attributes
}
export interface SpecialUser extends User {
attributes: SpecialAttributes //overrides original attributes
}

有完全相同的问题,但希望将其保留为接口而不是类型。这与 skovy 的答案类似,只是将交集移动到界面中:

interface User {
attributes: {
full_name: string;
};
}
interface SpecialUser extends User {
attributes: {
occupation: string;
} & User["attributes"];
};
const user: SpecialUser = {
attributes: {
occupation: "job",
full_name: "name"
}
};

打字稿游乐场

最新更新