Union Type Shape Area Calculator
Define a discriminated union type Shape that can be Circle | Rectangle. Circle has kind, radius. Rectangle has kind, width, height. Write a function that calculates area using a type guard switch statement.
TypeScript's discriminated unions allow you to define a variable that can hold one of several types, distinguished by a common literal property (kind). Type guards using switch statements narrow the type within each case branch.
For Circle, area = pi * radius^2. For Rectangle, area = width * height.
Discriminated unions are a powerful TypeScript pattern where each variant of a union type shares a common literal property (the discriminant). In this case, the 'kind' property distinguishes Circle from Rectangle shapes.
TypeScript's control flow analysis narrows the type within each branch of a switch or if-else chain, giving access to type-specific properties without unsafe type assertions.
Discriminated unions are one of TypeScript's most powerful features for modeling domain data. Each variant has a literal property (the discriminant) that TypeScript uses to narrow the type in control flow analysis.
This pattern is commonly used in state management, API response handling, and form validation where a value can be one of several known shapes.
Example Input & Output
Algorithm Flow

Solution Approach
Best Answers
function calculateArea(shape: any): number {
if (shape.kind === "circle") {
return Math.round(3.14 * shape.radius * shape.radius * 100) / 100;
}
return shape.width * shape.height;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
