Logo
Section 1 / 12

与类型、接口和泛型的结合

在本节课中,我们将学习如何交叉类型、接口和泛型。

导入

与类型、接口和泛型的结合

在本节课中,我们将学习如何交叉类型、接口和泛型。

TypeScript 可以通过多种方式组合类型。第一种方式是使用与运算符 & 定义交集类型。最终,该类型将包含所有成员的总和。

1type T1 = { x: string }; 2type T2 = { y: number }; 3type T3 = { z: boolean }; 4type IntersectType1 = T1 & T2 & T3; 5type IntersectType2 = T1 & T2; 6type IntersectType3 = T3 & T1; 7const inter1: T1 = { x: "x1", y: 2 }; // 无法编译:T1 中不存在 y 8const inter2: T1 & T2 = { x: "x1", y: 2 }; // 编译通过 9const inter3: IntersectType2 = { x: "x1", y: 2 }; // 编译通过

接口也适用于交集。

1interface I1 { 2 x: string; 3} 4interface I2 { 5 y: number; 6} 7interface I3 { 8 z: boolean; 9} 10type IntersectWithInterface = I1 & I2 & I3; 11const with3Interfaces: IntersectWithInterface = { x: "1", y: 1, z: true };

另一方面,交集也可以用于扩展其他接口。然而,交集在动态组合类型时表现尤为出色。如果使用接口继承,则需要创建额外的接口来继承已有接口,这可能会导致代码库变得冗杂,尤其是当需要组合的类型较多时。

1interface CombineI1 extends I1, I2, I3 {} 2interface CombineI2 extends I1, I2 {} 3interface CombineI3 extends I3, I1 {}

将交集结果赋值给变量比使用继承更具可重用性和实用性。但同时,在参数或返回类型中临时使用交集也非常方便。

1function intersectOnTheFly(t: I1 & I2) { }

交集类型可以与泛型结合,以提供更大的灵活性。在下面的例子中,函数是泛型的,并在返回类型中组合了两个泛型类型。

1function intersectGeneric<TT1, TT2>(t1: TT1, t2: TT2): TT1 & TT2 { 2 const returnValue = <TT1 & TT2>{}; 3 for (let index in t1) { 4 (returnValue as TT1)[index] = t1[index]; 5 } 6 for (let index in t2) { 7 (returnValue as TT2)[index] = t2[index]; 8 } 9 return returnValue; 10}

索引签名

字面量类型、缩小类型和 const