Solución
solution.tsTypeScript
type Shape =
| { type: 'circle'; radius: number }
| { type: 'rect'; width: number; height: number }
| { type: 'triangle'; base: number; height: number };
// Función auxiliar para manejar casos 'shape.type' que
// puedan ser añadidos con posterioridad al 'type Shape'
// y que, por tanto, no es un 'case' del switch ahora mismo
function AssertNever ( value: never): never {
throw new Error(`No way José: ${JSON.stringify(value)}`);
}
export function calcShapeArea(shape: Shape): number {
// Calcula y retorna el área de la forma usando un switch exhaustivo
switch(shape.type) {
case 'circle':
return Math.PI * shape.radius**2;
case 'rect':
return shape.height * shape.width;
case 'triangle':
return (shape.base * shape.height) / 2;
// Si todo va bien nunca debería llegar aquí, al 'default':
default:
return AssertNever(shape)
}
}0respuestas