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