简体   繁体   中英

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.

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:

export interface EmployeeWithDepartment extends Employee {
    departmentDetails: Department
}

Is there a way I can create the EmployeeDetails interface without actually creating EmployeeWithDepartment ? Some way to include both Employee and Department at once in the EmployeeDetails interface?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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