Solución

@estouchedisindo·17/5/2026TypeScript
solution.tsTypeScript
type Circle = { kind: "circle"; radius: number };
type Rectangle = { kind: "rect"; width: number; height: number };
type Triangle = { kind: "triangle"; base: number; height: number };
type Shape = Circle | Rectangle | Triangle;

export function calculateArea(shape: Shape): number {

  // Guarda de tipos (Type Guard)
  // en la condición del switch() shape: Shape
  switch (shape.kind) {
    // Implementa cada caso de la union y agrega el chequeo exhaustivo
    // en case 'circle', tsc ya sabe que shape: 'circle' => infiere sus props.
    case "circle":
      return Math.PI * (shape.radius ** 2)
      break
    // ídem
    case "rect":
      return shape.width * shape.height
      break
    // ídem
    case "triangle":
      return (shape.base * shape.height) / 2
      break
    default:
      const _: never = shape
      return _;
  }
}
0respuestas
Respuestas

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.