0
0
Typescriptprogramming~30 mins

Exhaustive pattern matching in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Define the Shape union type and create a shape variable
Define a TypeScript union type called Shape with three variants: { kind: 'circle', radius: number }, { kind: 'rectangle', width: number, height: number }, and { kind: 'triangle', base: number, height: number }. Then create a variable called shape with the value { kind: 'circle', radius: 5 }.
Typescript
Need a hint?

Use a union type with | to combine the three shape object types. Then assign the shape variable exactly as shown.

2
Add a helper variable for Pi
Create a constant variable called pi and set it to 3.14.
Typescript
Need a hint?

Use const pi = 3.14; to define the helper variable.

3
Use a switch statement for exhaustive pattern matching
Write a switch statement on shape.kind with cases for 'circle', 'rectangle', and 'triangle'. Calculate the area for each shape and store it in a variable called area. For 'circle', use pi * radius * radius. For 'rectangle', use width * height. For 'triangle', use 0.5 * base * height. Add a default case that throws an error with the message 'Unknown shape'.
Typescript
Need a hint?

Use switch (shape.kind) and assign the calculated area to area inside each case. Don't forget break; statements.

4
Print the calculated area
Write a console.log statement to print the text Area: followed by the value of the area variable.
Typescript
Need a hint?

Use console.log("Area:", area); to print the result.