简体   繁体   English

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

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

Language=Typescript语言=打字稿
I want to use the aggregation of 2 interfaces as the value of an indexable-type in a 3rd interface.我想使用 2 个接口的聚合作为第三个接口中可索引类型的值。

Interface 1:接口一:

export interface Employee {
    id: string
    name: string
}

Interface 2:接口二:

export interface Department {
    department: string
}

Now I want to write an interface equivalent of this:现在我想写一个等价的接口:

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

where EmployeeWithDepartment is:其中EmployeeWithDepartment是:

export interface EmployeeWithDepartment extends Employee {
    departmentDetails: Department
}

Is there a way I can create the EmployeeDetails interface without actually creating EmployeeWithDepartment ?有没有一种方法可以在实际创建EmployeeWithDepartment的情况下创建EmployeeDetails接口? Some way to include both Employee and Department at once in the EmployeeDetails interface?在 EmployeeDetails 界面中同时包含 Employee 和 Department 的某种方式?

PS: I've been using JS & TypeScript only for a week now, so I may not be aware of some concepts that can easily accomplish this. PS:我已经使用 JS & TypeScript 一个星期了,所以我可能不知道一些可以轻松实现这一点的概念。

I believe that what you are looking for is a type intersection, the & opertator.我相信您正在寻找的是一个类型交集,即&运算符。 It combines all properties of two types.它结合了两种类型的所有属性。

For example:例如:

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

To use that here in your types, you could do something like:要在您的类型中使用它,您可以执行以下操作:

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

Playground 操场


This is probably a good page to read: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces这可能是一个很好的阅读页面: 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