0
0
Typescriptprogramming~15 mins

Type narrowing with typeof in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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 10
Create a variable called input2 with the value '20'
Create a variable called result that will hold the final output
Use typeof to check the types of input1 and input2
If both are numbers, add them and assign to result
If both are strings, concatenate them and assign to result
If types differ, convert both to strings and concatenate, then assign to result
Print 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
1
Create input variables
Create a variable called input1 and set it to the number 10. Create another variable called input2 and set it to the string '20'.
Typescript
Need a hint?

Use let to create variables and assign the exact values given.

2
Create result variable
Create a variable called result and set it to an empty string ''.
Typescript
Need a hint?

Initialize result as an empty string to hold the output later.

3
Use typeof to narrow types and assign result
Use typeof to check the types of input1 and input2. If both are 'number', add them and assign to result. Else if both are 'string', concatenate them and assign to result. Otherwise, convert both to strings and concatenate, then assign to result.
Typescript
Need a hint?

Use if, else if, and else blocks with typeof checks to handle each case.

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

Use console.log(result); to display the final output.