Why type narrowing is needed
📖 Scenario: Imagine you have a box that can hold either a number or a string. You want to do different things depending on what is inside the box. But before you can safely use the box's content, you need to check what type it is. This is where type narrowing helps.
🎯 Goal: You will write a simple TypeScript program that shows why type narrowing is needed by checking the type of a variable and then safely using it.
📋 What You'll Learn
Create a variable called
value that can hold either a number or a string.Create a variable called
isNumber to help check if value is a number.Use an
if statement to narrow the type of value based on isNumber.Print different messages depending on whether
value is a number or a string.💡 Why This Matters
🌍 Real World
In real apps, variables can hold different types. Type narrowing helps avoid mistakes by checking types before using them.
💼 Career
Understanding type narrowing is important for writing safe and bug-free TypeScript code in professional software development.
Progress0 / 4 steps