Why union types are needed
📖 Scenario: Imagine you are building a simple app that accepts user input. Sometimes the input is a number, and sometimes it is a word. You want to write code that can handle both cases safely.
🎯 Goal: You will create a variable that can hold either a number or a string using union types. Then you will write code to check the type and handle each case properly.
📋 What You'll Learn
Create a variable called
userInput that can hold a number or a stringCreate a variable called
userInput and assign a number to itWrite an
if statement that checks if userInput is a stringPrint different messages depending on whether
userInput is a string or a number💡 Why This Matters
🌍 Real World
Many apps accept user input that can be different types, like numbers or text. Union types help handle these safely.
💼 Career
Understanding union types is important for writing flexible and error-free TypeScript code in real projects.
Progress0 / 4 steps