0
0
Typescriptprogramming~15 mins

Why union types are needed in Typescript - See It in Action

Choose your learning style9 modes available
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 string
Create a variable called userInput and assign a number to it
Write an if statement that checks if userInput is a string
Print 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
1
Create a union type variable
Create a variable called userInput that can hold either a number or a string. Assign the number 42 to it.
Typescript
Need a hint?

Use the | symbol to combine types in TypeScript.

2
Assign a new value to the union type variable
Assign the string "hello" to the variable userInput.
Typescript
Need a hint?

You can assign either a number or a string to userInput.

3
Check the type of the union variable
Write an if statement that checks if userInput is a string using typeof userInput === "string".
Typescript
Need a hint?

Use typeof to check the type inside the if statement.

4
Print the result based on the type
Run the code and observe the output. It should print User input is a string: hello.
Typescript
Need a hint?

Check the console output to see the message.