[英]How to create an interface in Typescript using two other interfaces without inheritance?
语言=打字稿
我想使用 2 个接口的聚合作为第三个接口中可索引类型的值。
接口一:
export interface Employee {
id: string
name: string
}
接口二:
export interface Department {
department: string
}
现在我想写一个等价的接口:
export interface EmployeeDetails { employees: { [key: string]: { employeeDetails: EmployeeWithDepartment } } }
其中EmployeeWithDepartment
是:
export interface EmployeeWithDepartment extends Employee {
departmentDetails: Department
}
有没有一种方法可以在不实际创建EmployeeWithDepartment
的情况下创建EmployeeDetails
接口? 在 EmployeeDetails 界面中同时包含 Employee 和 Department 的某种方式?
PS:我已经使用 JS & TypeScript 一个星期了,所以我可能不知道一些可以轻松实现这一点的概念。
我相信您正在寻找的是一个类型交集,即&
运算符。 它结合了两种类型的所有属性。
例如:
interface A { a: number }
interface B = { b: string }
type C = A & B // { a: number, b: string }
要在您的类型中使用它,您可以执行以下操作:
export interface EmployeeDetails {
employees: {
[key: string]: {
employeeDetails: Employee & { departmentDetails: Department }
}
}
}
这可能是一个很好的阅读页面: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.