[ts] 排他联合类型问题?-灵析社区

爱打瞌睡的三角龙

// 目前需要这样的结构 interface IChildLine { isLine: boolean points: number[] } interface IChildCircle { isCircle: boolean points: number[] } interface ITab{ children:(IChildCircle | IChildLine)[] } // 也就是说 ITab 的 children 要么是 isCircle 要么是 isLine ,在一个对象里不能同时存在 我感觉有优化空间,有大佬知道怎么优化吗?

阅读量:18

点赞量:0

问AI
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); } });