Exhaustive pattern matching
📖 Scenario: You are building a simple program to identify different shapes and calculate their areas. Each shape has a specific set of properties. You want to use exhaustive pattern matching to handle all shape types safely.
🎯 Goal: Create a TypeScript program that defines a union type for shapes, uses exhaustive pattern matching with match or switch statements, and calculates the area for each shape type.
📋 What You'll Learn
Define a union type
Shape with three variants: circle, rectangle, and triangle.Create a variable
shape with a specific shape object.Add a helper variable
pi with the value 3.14.Use a
switch statement on shape.kind to calculate the area for each shape.Include an exhaustive
default case that throws an error if an unknown shape is encountered.Print the calculated area.
💡 Why This Matters
🌍 Real World
Pattern matching helps safely handle different data types or variants in programs, such as processing different shapes, events, or messages.
💼 Career
Understanding exhaustive pattern matching is important for writing robust TypeScript code that handles all cases and avoids runtime errors.
Progress0 / 4 steps