📖 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
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
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
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
Hint
Use console.log(result); to display the final output.
Practice
(1/5)
1. What does the typeof operator do in TypeScript?
easy
A. It converts a variable to a string.
B. It changes the type of a variable.
C. It declares a new type.
D. It checks the type of a variable at runtime.
Solution
Step 1: Understand the purpose of typeof
The typeof operator is used to check the type of a variable during the program's execution (runtime).
Step 2: Differentiate from other options
It does not change, declare, or convert types; it only inspects the type.
Final Answer:
It checks the type of a variable at runtime. -> Option D
Quick Check:
typeof checks type at runtime [OK]
Hint: Remember: typeof tells you the type, it doesn't change it. [OK]
Common Mistakes:
Thinking typeof changes the variable's type
Confusing typeof with type declaration
Assuming typeof converts values to strings
2. Which of the following is the correct syntax to narrow a variable value to a string using typeof?
easy
A. if (typeof value === 'string') { }
B. if (typeof value = 'string') { }
C. if (typeof value == string) { }
D. if (typeof value === string) { }
Solution
Step 1: Check correct equality operator and string literal
The correct way to compare is using triple equals === and the type name as a string literal, like 'string'.
Step 2: Identify syntax errors in other options
if (typeof value = 'string') { } uses single equals which is assignment, not comparison. Options A and C miss quotes around 'string'.
Final Answer:
if (typeof value === 'string') { } -> Option A
Quick Check:
Use === and quotes for typeof checks [OK]
Hint: Use === and quotes around type names in typeof checks. [OK]
Common Mistakes:
Using single = instead of ===
Forgetting quotes around type names
Using == instead of ===
3. What will be the output of this TypeScript code?
function checkType(x: string | number) {
if (typeof x === 'string') {
return x.toUpperCase();
} else {
return x + 10;
}
}
console.log(checkType('hello'));
console.log(checkType(5));
medium
A. HELLO and 510
B. hello and 15
C. HELLO and 15
D. Error at runtime
Solution
Step 1: Analyze the input 'hello'
Since 'hello' is a string, typeof x === 'string' is true, so x.toUpperCase() returns 'HELLO'.
Step 2: Analyze the input 5
Since 5 is a number, the else block runs, returning 5 + 10 = 15.
Final Answer:
HELLO and 15 -> Option C
Quick Check:
String upper + number addition = HELLO, 15 [OK]
Hint: Check typeof to pick string or number logic correctly. [OK]
Common Mistakes:
Concatenating number and string instead of adding
Calling string methods on numbers
Confusing toUpperCase output
4. Identify the error in this TypeScript code using typeof for type narrowing:
function process(value: string | boolean) {
if (typeof value === 'boolean') {
return value.toUpperCase();
} else {
return value ? 'Yes' : 'No';
}
}
medium
A. Calling toUpperCase on a boolean value
B. Using typeof with boolean type
C. Missing return type annotation
D. Incorrect if-else structure
Solution
Step 1: Check the type narrowing condition
The condition typeof value === 'boolean' correctly narrows value to boolean.
Step 2: Identify method call on wrong type
Inside this block, calling value.toUpperCase() is invalid because booleans do not have this method.
Final Answer:
Calling toUpperCase on a boolean value -> Option A
Quick Check:
Boolean has no toUpperCase method [OK]
Hint: Check method calls match the narrowed type. [OK]
Common Mistakes:
Assuming booleans have string methods
Ignoring type narrowing effect
Confusing boolean and string logic
5. You have a function that accepts input: string | number | boolean. You want to return: - The length of the string if input is a string, - The number multiplied by 2 if input is a number, - The string 'True' or 'False' if input is a boolean.
Which of the following implementations correctly uses typeof for type narrowing?
hard
A. function handle(input: string | number | boolean) {
if (typeof input === 'boolean') {
return input.length;
} else if (typeof input === 'string') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
}
B. function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.length;
} else if (typeof input === 'number') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
}
C. function handle(input: string | number | boolean) {
if (typeof input === 'number') {
return input.length;
} else if (typeof input === 'boolean') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
}
D. function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.toUpperCase();
} else if (typeof input === 'number') {
return input + 2;
} else {
return input ? 'True' : 'False';
}
}
Solution
Step 1: Check string handling
function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.length;
} else if (typeof input === 'number') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
} returns input.length for strings, which is correct. function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.toUpperCase();
} else if (typeof input === 'number') {
return input + 2;
} else {
return input ? 'True' : 'False';
}
} returns input.toUpperCase(), which is not requested.
Step 2: Check number handling
function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.length;
} else if (typeof input === 'number') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
} multiplies number by 2, as required. function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.toUpperCase();
} else if (typeof input === 'number') {
return input + 2;
} else {
return input ? 'True' : 'False';
}
} adds 2, which is incorrect. Options B and C misuse length or multiplication on wrong types.
Step 3: Check boolean handling
function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.length;
} else if (typeof input === 'number') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
} returns 'True' or 'False' strings correctly. Others mix up boolean logic or return wrong types.
Final Answer:
function handle(input: string | number | boolean) {
if (typeof input === 'string') {
return input.length;
} else if (typeof input === 'number') {
return input * 2;
} else {
return input ? 'True' : 'False';
}
} -> Option B
Quick Check:
Match typeof checks with correct operations [OK]
Hint: Match each typeof check with correct operation for that type. [OK]
Common Mistakes:
Calling string methods on numbers or booleans
Using length on numbers or booleans
Mixing up operations for each type
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.