0
0
Typescriptprogramming~30 mins

Type predicates in practice in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Type predicates in practice
📖 Scenario: Imagine you are building a simple app that handles different shapes. Each shape can be a Circle or a Square. You want to write code that checks which shape you have and then calculates the area correctly.
🎯 Goal: You will create a list of shapes, write a type predicate function to check if a shape is a Circle, then use that function to calculate and print the area of each shape.
📋 What You'll Learn
Create a union type called Shape that can be a Circle or a Square.
Create a type predicate function called isCircle that checks if a shape is a Circle.
Use a for loop to go through an array of shapes and calculate the area using the type predicate.
Print the area of each shape with a message.
💡 Why This Matters
🌍 Real World
Type predicates help you write safer code when working with data that can be different types, like shapes, user inputs, or API responses.
💼 Career
Understanding type predicates is important for TypeScript developers to avoid runtime errors and improve code quality in real projects.
Progress0 / 4 steps
1
Create the shapes array
Create a type called Circle with a radius number property, a type called Square with a side number property, and a union type called Shape that can be either Circle or Square. Then create a constant array called shapes with these exact values: a Circle with radius 5, a Square with side 10, and a Circle with radius 3.
Typescript
Need a hint?

Start by defining the types exactly as described, then create the array with the exact objects.

2
Write the type predicate function
Write a function called isCircle that takes a parameter shape of type Shape and returns a type predicate shape is Circle. The function should return true if shape has the property radius, otherwise false.
Typescript
Need a hint?

Use the syntax function isCircle(shape: Shape): shape is Circle and check if radius exists on shape.

3
Calculate areas using the type predicate
Use a for loop with the variable shape to go through the shapes array. Inside the loop, use the isCircle function to check if shape is a Circle. If it is, calculate the area as Math.PI * shape.radius * shape.radius. Otherwise, calculate the area as shape.side * shape.side. Store the area in a variable called area.
Typescript
Need a hint?

Use if (isCircle(shape)) to check the type and calculate area accordingly.

4
Print the area of each shape
Inside the for loop, after calculating the area, write a console.log statement that prints exactly: Area: followed by the area rounded to 2 decimal places using area.toFixed(2).
Typescript
Need a hint?

Use console.log("Area: " + area.toFixed(2)) to print the area with two decimals.