在TypeScript中,我们可以通过使用联合类型和类型保护来避免在switch语句中使用类型转换。以下是一个示例:
type Shape = Circle | Square;
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
// 使用类型保护,直接可以访问Circle接口的属性
return Math.PI * shape.radius ** 2;
case "square":
// 使用类型保护,直接可以访问Square接口的属性
return shape.sideLength ** 2;
default:
throw new Error("Invalid shape");
}
}
const circle: Circle = { kind: "circle", radius: 5 };
const square: Square = { kind: "square", sideLength: 5 };
console.log(area(circle)); // 输出: 78.53981633974483
console.log(area(square)); // 输出: 25
在上面的示例中,我们定义了两个接口Circle
和Square
,它们都有一个相同的属性kind
来标识形状的类型。然后,我们定义了一个Shape
类型,它是Circle
和Square
的联合类型。
在area
函数中,我们使用switch语句根据shape.kind
的值来执行不同的逻辑。由于我们知道每个分支的类型,TypeScript可以通过类型保护将shape
的类型缩小为特定的接口类型,从而可以直接访问相应接口的属性。
这种方法避免了在switch语句中进行类型转换,提供了更好的类型安全性和可读性。