0
0
Typescriptprogramming~30 mins

Discriminated unions in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Discriminated Unions in TypeScript
πŸ“– Scenario: You are building a simple system to handle different shapes in a drawing app. Each shape has a type and specific properties. You want to write code that can safely work with these shapes by checking their type.
🎯 Goal: Create a TypeScript program that uses discriminated unions to define different shapes, then write code to calculate the area of each shape based on its type.
πŸ“‹ What You'll Learn
Define a union type called Shape with discriminated property kind
Include three shapes: circle, rectangle, and triangle
Write a function calculateArea that takes a Shape and returns its area
Use a switch statement on shape.kind to handle each shape type
Print the area for each shape in a list
πŸ’‘ Why This Matters
🌍 Real World
Discriminated unions help safely handle different data types in one variable, common in apps that process varied inputs like shapes, events, or messages.
πŸ’Ό Career
Understanding discriminated unions is important for TypeScript developers to write clear, type-safe code that prevents bugs and improves maintainability.
Progress0 / 4 steps
1
Define the Shape union type
Create a TypeScript type called Shape that is a union of three object types. Each object must have a kind property with values 'circle', 'rectangle', or 'triangle'. Add these properties: radius: number for circle, width: number and height: number for rectangle, and base: number and height: number for triangle.
Typescript
Need a hint?

Use a union type with | and make sure each shape has a kind property with a unique string literal.

2
Create an array of shapes
Create a constant array called shapes with three elements. Each element should be an object matching one of the Shape types you defined: a circle with radius 5, a rectangle with width 10 and height 4, and a triangle with base 6 and height 3.
Typescript
Need a hint?

Make sure the array is called shapes and each object matches the Shape type exactly.

3
Write the calculateArea function
Write a function called calculateArea that takes one parameter shape of type Shape. Use a switch statement on shape.kind to return the area for each shape: circle area is Ο€ x radiusΒ² (use 3.14 for Ο€), rectangle area is width x height, triangle area is 0.5 x base x height.
Typescript
Need a hint?

Use a switch on shape.kind and return the correct formula for each shape.

4
Print the area of each shape
Use a for loop to go through each shape in the shapes array. Inside the loop, print a message like Area of circle: 78.5 using console.log. Use the calculateArea function to get the area.
Typescript
Need a hint?

Use a for...of loop and console.log with a template string to print the area for each shape.