在 TypeScript 中,如何向接口中的对象类型添加属性?

Ind*_*ool 4 javascript object typescript

我试图了解如何合并声明接口,但我希望向对象文字类型添加属性,而不是向接口本身添加字段。

我在库中定义了一个类型,如下所示:

interface DefaultSession {
    user?: {
      name?: string | null;
      email?: string | null;
      image?: string | null;
    };
    expires: ISODateString;
}
Run Code Online (Sandbox Code Playgroud)

我知道,如果我想在不更改名称的情况下向该界面添加一个字段,我可以简单地重新打开并声明:

interface DefaultSession {
    role?: string
}
Run Code Online (Sandbox Code Playgroud)

我一直在研究 Typescript 手册,但我找不到一种方法将声明角色合并为用户下的属性以产生如下类型:

interface DefaultSession {
    user?: {
        name?: string | null;
        email?: string | null;
        image?: string | null;
        role?: string | null;
    };
    expires: ISODateString;
}
Run Code Online (Sandbox Code Playgroud)

dpi*_*nov 6

您正在寻找的是交叉类型:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以按原样使用它或在您的班级中实现它。此外,如果您希望自定义类型具有相同的名称,则只需使用别名引用库类型即可。

如果库中有回调,您可以覆盖参数类型,如下所示:

// 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;
});
Run Code Online (Sandbox Code Playgroud)