Reputation: 23
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.
Upvotes: 1
Views: 892
Reputation: 186984
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 }
}
}
}
This is probably a good page to read: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces
Upvotes: 1