Type narrowing with typeof in Typescript - Time & Space Complexity
We want to see how the time it takes to run code changes when we use type checks with typeof.
How does checking a variable's type affect the speed as the input grows?
Analyze the time complexity of the following code snippet.
function processValue(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
} else {
return value * 2;
}
}
const inputs = ["hello", 10, "world", 5];
const results = inputs.map(processValue);
This code checks each item's type and processes it differently, then applies this to all items in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mapmethod loops over each item in the array. - How many times: Once for every item in the input array.
Each new item adds one more type check and processing step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and processings |
| 100 | About 100 type checks and processings |
| 1000 | About 1000 type checks and processings |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[X] Wrong: "Type checking with typeof makes the code run slower in a way that depends on the type itself."
[OK] Correct: The type check cost is the same for each item and does not depend on the type's content or size, only on how many items we check.
Understanding how type checks affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.
"What if we replaced map with a nested loop that processes pairs of items? How would the time complexity change?"
Practice
typeof operator do in TypeScript?Solution
Step 1: Understand the purpose of
Thetypeoftypeofoperator 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 DQuick Check:
typeof checks type at runtime [OK]
- Thinking typeof changes the variable's type
- Confusing typeof with type declaration
- Assuming typeof converts values to strings
value to a string using typeof?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 AQuick Check:
Use === and quotes for typeof checks [OK]
- Using single = instead of ===
- Forgetting quotes around type names
- Using == instead of ===
function checkType(x: string | number) {
if (typeof x === 'string') {
return x.toUpperCase();
} else {
return x + 10;
}
}
console.log(checkType('hello'));
console.log(checkType(5));Solution
Step 1: Analyze the input 'hello'
Since 'hello' is a string,typeof x === 'string'is true, sox.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 CQuick Check:
String upper + number addition = HELLO, 15 [OK]
- Concatenating number and string instead of adding
- Calling string methods on numbers
- Confusing toUpperCase output
typeof for type narrowing:function process(value: string | boolean) {
if (typeof value === 'boolean') {
return value.toUpperCase();
} else {
return value ? 'Yes' : 'No';
}
}Solution
Step 1: Check the type narrowing condition
The conditiontypeof value === 'boolean'correctly narrows value to boolean.Step 2: Identify method call on wrong type
Inside this block, callingvalue.toUpperCase()is invalid because booleans do not have this method.Final Answer:
Calling toUpperCase on a boolean value -> Option AQuick Check:
Boolean has no toUpperCase method [OK]
- Assuming booleans have string methods
- Ignoring type narrowing effect
- Confusing boolean and string logic
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?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'; } } returnsinput.lengthfor 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'; } } returnsinput.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 BQuick Check:
Match typeof checks with correct operations [OK]
- Calling string methods on numbers or booleans
- Using length on numbers or booleans
- Mixing up operations for each type
Ready to prove it?
Pass the test and this pattern moves unknown
