Type narrowing with typeof
📖 Scenario: Imagine you are building a simple calculator that can add numbers or concatenate strings. To do this safely, you need to check the type of inputs before processing them.
🎯 Goal: Create a TypeScript program that uses typeof to narrow types and handle numbers and strings differently.
📋 What You'll Learn
Create a variable called
input1 with the value 10Create a variable called
input2 with the value '20'Create a variable called
result that will hold the final outputUse
typeof to check the types of input1 and input2If both are numbers, add them and assign to
resultIf both are strings, concatenate them and assign to
resultIf types differ, convert both to strings and concatenate, then assign to
resultPrint the
result💡 Why This Matters
🌍 Real World
Type narrowing helps prevent errors when working with variables that can hold different types, such as user inputs or API data.
💼 Career
Understanding type narrowing is important for writing safe and bug-free TypeScript code in real-world applications.
Progress0 / 4 steps