[英]In TypeScript, How do I go about adding a property to an object type in an Interface?
我试图了解如何合并声明接口,但不是向接口本身添加字段,而是希望向 object 文字类型添加一个属性。
我在库中定义了一个类型,如下所示:
interface DefaultSession {
user?: {
name?: string | null;
email?: string | null;
image?: string | null;
};
expires: ISODateString;
}
我知道如果我想在这个界面中添加一个字段而不更改名称,我可以简单地重新打开并声明:
interface DefaultSession {
role?: string
}
我一直在研究 Typescript 手册,但我找不到将声明角色合并为用户下的属性以产生如下类型的方法:
interface DefaultSession {
user?: {
name?: string | null;
email?: string | null;
image?: string | null;
role?: string | null;
};
expires: ISODateString;
}
您正在寻找的是交叉点类型:
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html
只需声明您的自定义类型,如下所示:
interface DefaultSession {
user?: {
name?: string | null;
email?: string | null;
image?: string | null;
};
expires: ISODateString;
}
type CustomDefaultSession = DefaultSession & {
user?: {
role?: string | null;
}
}
然后您可以按原样使用它,或者为您的 class 实施它。 此外,如果您希望自定义类型具有相同的名称,则只需使用别名引用库类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.