主题
交叉类型
交叉类型使用 & 把多个类型合并成一个类型,新类型需要同时满足所有成员类型的要求。
基本示例
ts
interface Person {
name: string
}
interface Contact {
phone: string
}
type PersonDetail = Person & Contact
const user: PersonDetail = {
name: 'foo',
phone: '1234567890',
}适用场景
- 合并多个对象类型
- 在已有类型基础上补充字段
- 和泛型、工具类型组合使用
ts
type ApiResponse<T> = T & {
success: boolean
message: string
}注意事项
交叉类型不是“二选一”,而是“同时满足”。
ts
type A = { x: string }
type B = { y: number }
type C = A & B
const value: C = {
x: 'hello',
y: 1,
}