我试图了解如何合并声明一个接口(interface),但不是向接口(interface)本身添加一个字段,而是希望向对象文字类型添加一个属性。
我在库中定义了一个类型,如下所示:
interface DefaultSession {
user?: {
name?: string | null;
email?: string | null;
image?: string | null;
};
expires: ISODateString;
}
我知道如果我想在这个界面中添加一个字段而不更改名称,我可以简单地重新打开并声明:interface DefaultSession {
role?: string
}
我一直在研究 typescript 手册,但我找不到一种方法将声明 Angular 色合并为用户下的属性以产生如下类型: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)实现它。此外,如果您希望自定义类型具有相同的名称,则只需使用别名引用库类型。如果您在库中有回调,则可以覆盖参数类型,如下所示:
// Callback defined inside the library.
type LibraryCallback = (defaultSession: DefaultSession) => void;
// Function inside the library which accepts callback.
function libraryFunction(libraryCallback: LibraryCallback): void
{
// Do stuff...
}
// Application code which calls library function and changes callback argument type.
libraryFunction((customDefaultSession: CustomDefaultSession) =>
{
const role = customDefaultSession.user.role;
});
关于javascript - 在 TypeScript 中,如何将属性添加到接口(interface)中的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73244673/