繁体   English   中英

如何使用没有 inheritance 的其他两个接口在 Typescript 中创建接口?

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

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

接口一:

export interface Employee {
    id: string
    name: string
}

接口二:

export interface Department {
    department: string
}

现在我想写一个等价的接口:

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

其中EmployeeWithDepartment是:

export interface EmployeeWithDepartment extends Employee {
    departmentDetails: Department
}

有没有一种方法可以在实际创建EmployeeWithDepartment的情况下创建EmployeeDetails接口? 在 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 }
    }
  }
}

操场


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM