0
0
Typescriptprogramming~15 mins

Why type narrowing is needed in Typescript - See It in Action

Choose your learning style9 modes available
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
1
Create a variable with two possible types
Create a variable called value that can hold either the number 42 or the string "hello". Set it to 42.
Typescript
Need a hint?

Use the | symbol to say the variable can be more than one type.

2
Add a helper variable to check the type
Create a variable called isNumber that is true if value is a number, otherwise false. Use typeof value === 'number'.
Typescript
Need a hint?

Use typeof to check the type of a variable.

3
Use type narrowing with an if statement
Use an if statement with isNumber to check if value is a number. Inside the if, create a variable called result that is value * 2. In the else, create result that is value.toUpperCase().
Typescript
Need a hint?

Inside the if, TypeScript knows value is a number. Inside else, it knows value is a string.

4
Print the result
Write console.log(result) to print the value of result.
Typescript
Need a hint?

Use console.log to show the result on the screen.