1

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.

1 Answers1

1

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

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Quoting from the handbook, "For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type." @alex-wayne generally, what is advisable to use? What are the trade-offs? – Garvit Jain Apr 21 '21 at 07:12
  • 1
    This is a large topic I could hope to summarize in a comment. I would recommend using interfaces for the most part, but throwing in an intersection like this if it makes the types easier to read and maintain isn't a bad thing. See this link for much more info: https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types – Alex Wayne Apr 21 '21 at 16:26