0
0
Typescriptprogramming~15 mins

typeof type guards in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using typeof Type Guards in TypeScript
📖 Scenario: 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 type guards to handle inputs differently based on whether they are numbers or strings.
📋 What You'll Learn
Create variables with different types (number and string)
Create a helper variable to hold the result
Use typeof type guards to check the type of inputs
Print the final result
💡 Why This Matters
🌍 Real World
Type guards help prevent errors when working with different data types, especially in user input or API data.
💼 Career
Understanding type guards is important for writing safe and reliable TypeScript code in web development and software engineering.
Progress0 / 4 steps
1
Create input variables
Create two variables called input1 and input2. Set input1 to the number 10 and input2 to the string "20".
Typescript
Need a hint?

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

2
Create a 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 store the final output.

3
Use typeof type guards to combine inputs
Use if statements with typeof to check if both input1 and input2 are numbers. If yes, add them and assign to result. Otherwise, convert both to strings and concatenate them, then assign to result.
Typescript
Need a hint?

Use typeof to check types and handle both cases separately.

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

Use console.log(result) to show the final output.