TypeScript 中的交叉类型(Intersection Types)是一种强大的类型构造,允许多个类型组合成一个新类型,新类型将具有所有原类型的特性。交叉类型使用 &
运算符来定义,以下是详细介绍和几个示例:
定义
交叉类型使用 &
运算符将多个类型合并在一起,如下所示:
type Type1 = {
property1: number };
type Type2 = {
property2: string };
type CombinedType = Type1 & Type2;
在上面的示例中,CombinedType
是 Type1
和 Type2
的交叉类型,它具有 property1
和 property2
两个属性。
合并对象类型
type Person = {
name: string; age: number };
type Address = {
street: string; city: string };
type PersonWithAddress = Person & Address;
const personWithAddress: PersonWithAddress = {
name: 'John',
age: 30