如何在没有继承的情况下使用另外两个接口在 Typescript 中创建一个接口?

How to create an interface in Typescript using two other interfaces without inheritance?

语言=打字稿
我想使用 2 个接口的聚合作为第 3 个接口中可索引类型的值。

接口 1:

export interface Employee {
    id: string
    name: string
}

接口 2:

export interface Department {
    department: string
}

现在我想编写一个与此等效的接口:

export interface EmployeeDetails {
  employees: {
    [key: string]: {
      employeeDetails: EmployeeWithDepartment
    }
  }
}

其中 EmployeeWithDepartment 是:

export interface EmployeeWithDepartment extends Employee {
    departmentDetails: Department
}

有没有一种方法可以创建 EmployeeDetails 界面 而无需 实际创建 EmployeeWithDepartment?在 EmployeeDetails 界面中同时包含 Employee 和 Department 的一些方法?

PS: 我使用 JS 和 TypeScript 才一个星期,所以我可能不知道一些可以轻松实现这一点的概念。

我相信您正在寻找的是类型交集,即 & 运算符。它结合了两种类型的所有属性。

例如:

interface A { a: number }
interface B = { b: string }
type C = A & B // { a: number, b: string }

要在您的类型中使用它,您可以这样做:

export interface EmployeeDetails {
  employees: {
    [key: string]: {
      employeeDetails: Employee & { departmentDetails: Department }
    }
  }
}

Playground


这可能是一个值得阅读的页面:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces