function handleComplexUnion(data: ComplexUnion): string | number {
switch (data.type) {
case 'user':
return `User: ${data.name}, Age: ${data.age}`;
case 'product':
return `Product: ${data.name}, Price: ${data.price}`;
case 'order':
return data.items.reduce((total, item) => total + item.quantity * 1, 0);
}
}
优化思路及原因
- 使用
switch
语句:相比多个 if - else
语句,switch
语句在处理离散值(如这里的 type
字段)时通常具有更好的性能。在 if - else
链中,JavaScript 引擎需要依次检查每个条件,而 switch
语句在大多数情况下能够直接跳转到匹配的分支,减少不必要的比较操作。
- 直接通过
type
判断:由于 ComplexUnion
联合类型已经明确了不同类型的 type
字段,直接根据 type
进行判断是最直接有效的方式,避免了复杂的类型断言或其他间接判断方式,减少了额外的计算开销。这样既保证了代码的简洁性,又提高了执行效率。