0
0
Typescriptprogramming~30 mins

Exhaustive checking with never in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Exhaustive checking with never in TypeScript
📖 Scenario: You are building a simple program that handles different shapes. Each shape has a specific way to calculate its area. You want to make sure that if a new shape is added later, your program will remind you to handle it properly.
🎯 Goal: Create a TypeScript program that uses exhaustive checking with the never type to ensure all shape types are handled in a function.
📋 What You'll Learn
Create a union type called Shape with three shapes: circle, square, and rectangle
Create a variable called shape with a specific shape object
Create a function called calculateArea that uses a switch statement to handle each shape type
Use exhaustive checking with never in the calculateArea function to catch unhandled shapes
Print the area calculated by calculateArea
💡 Why This Matters
🌍 Real World
Exhaustive checking helps catch errors early when working with different types of data, such as shapes, events, or commands in real applications.
💼 Career
Understanding exhaustive checking with never is important for writing safe and maintainable TypeScript code, a valuable skill for frontend and backend developers.
Progress0 / 4 steps
1
Create the Shape union type and a shape variable
Create a union type called Shape with these exact types: { kind: 'circle', radius: number }, { kind: 'square', side: number }, and { kind: 'rectangle', width: 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 types. Then create the shape variable with the exact object.

2
Add the calculateArea function skeleton
Create a function called calculateArea that takes a parameter shape of type Shape and returns a number. Inside the function, add a switch statement on shape.kind with empty cases for 'circle', 'square', and 'rectangle'.
Typescript
Need a hint?

Define the function with the correct parameter and return type. Add a switch on shape.kind with cases for each shape kind.

3
Implement area calculations and add exhaustive checking
Inside the calculateArea function, return the correct area for each shape: for circle return Math.PI * shape.radius ** 2, for square return shape.side * shape.side, and for rectangle return shape.width * shape.height. After the switch, add a default case that assigns shape to a variable of type never to ensure exhaustive checking.
Typescript
Need a hint?

Calculate each area using the correct formula. Use a default case with a never variable to catch unhandled shapes.

4
Print the area of the shape
Write a console.log statement to print the result of calling calculateArea with the shape variable.
Typescript
Need a hint?

Call calculateArea(shape) and print the result using console.log.