// 定义图形类型的联合类型
type ShapeType = 'circle' |'rectangle';
// 定义圆形的类型
type Circle = {
type: 'circle';
center: [number, number];
radius: number;
};
// 定义矩形的类型
type Rectangle = {
type:'rectangle';
topLeft: [number, number];
bottomRight: [number, number];
};
// 定义所有图形的联合类型
type Shape = Circle | Rectangle;
// 绘制函数
function drawShape(shape: Shape) {
if (shape.type === 'circle') {
const [x, y] = shape.center;
console.log(`绘制圆形,圆心坐标: (${x}, ${y}),半径: ${shape.radius}`);
} else if (shape.type ==='rectangle') {
const [x1, y1] = shape.topLeft;
const [x2, y2] = shape.bottomRight;
console.log(`绘制矩形,左上角坐标: (${x1}, ${y1}),右下角坐标: (${x2}, ${y2})`);
}
}
- 类型定义:
- 首先定义了
ShapeType
联合类型,包含目前已知的图形类型。
- 然后分别为
circle
和rectangle
定义了具体的类型Circle
和Rectangle
,其中包含了对应图形所需的信息。
- 最后定义
Shape
联合类型,将Circle
和Rectangle
合并在一起。
- 绘制函数:
drawShape
函数接受一个Shape
类型的参数shape
。
- 在函数内部,通过
shape.type
判断图形类型,然后进行相应的绘制操作(这里简单地使用console.log
模拟绘制)。这种方式在未来添加新图形类型时,只需在ShapeType
联合类型、对应的图形类型定义以及drawShape
函数中添加新的判断逻辑即可,保证了类型安全和可维护性。