interface IChildBase {
points: number[];
}
interface IChildLine extends IChildBase {
type: 'line';
}
interface IChildCircle extends IChildBase {
type: 'circle';
}
type ChildShape = IChildCircle | IChildLine;
interface ITab {
children: ChildShape[];
}
// 用类型守卫来检查 children 的类型
function isLine(child: ChildShape): child is IChildLine {
return child.type === 'line';
}
function isCircle(child: ChildShape): child is IChildCircle {
return child.type === 'circle';
}
// 示例
const tab: ITab = {
children: [
{ type: 'circle', points: [1, 2, 3] },
{ type: 'line', points: [4, 5] }
]
};
tab.children.forEach(child => {
if (isLine(child)) {
console.log('This is a line.', child.points);
} else if (isCircle(child)) {
console.log('This is a circle.', child.points);
}
});