Code Logo

Union Type Shape Area Calculator

Published at24 Jul 2026
TypeScript Functions Medium 0 views
Like0

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

Example 1
Input
{"kind":"circle","radius":1}
Output
3.14
Example 2
Input
{"kind":"rectangle","width":3,"height":3}
Output
9
Example 3
Input
{"kind":"rectangle","width":4,"height":5}
Output
20
Example 4
Input
{"kind":"circle","radius":5}
Output
78.5
Example 5
Input
{"kind":"circle","radius":10}
Output
314

Algorithm Flow

Recommendation Algorithm Flow for Union Type Shape Area Calculator
Recommendation Algorithm Flow for Union Type Shape Area Calculator

Solution Approach

Define Shape = Circle | Rectangle where each has a 'kind' property. In the function, switch on shape.kind. TypeScript narrows the type in each case, giving access to type-specific properties without casting.

Best Answers

typescript - Approach 1
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;
}