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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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: stackoverflow.com/questions/37233735/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.