Bird
Raised Fist0
Typescriptprogramming~10 mins

Type narrowing with typeof in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type narrowing with typeof
Start with variable of union type
↓
Check typeof variable
↓
Narrow to string
↓
Use string methods
↓
End
We start with a variable that can be multiple types. Using typeof checks its actual type at runtime, then we safely use methods or operations for that specific type.
Execution Sample
Typescript
function example(x: string | number) {
  if (typeof x === 'string') {
    return x.toUpperCase();
  } else {
    return x.toFixed(2);
  }
}
This function checks if x is a string or number, then uses string or number methods accordingly.
Execution Table
StepActiontypeof xConditionBranch TakenOutput
1Input x = 'hello'stringtypeof x === 'string'?Yes'HELLO'
2Return x.toUpperCase()string--'HELLO'
3Input x = 3.1415numbertypeof x === 'string'?No-
4Else branch: return x.toFixed(2)number--'3.14'
💡 All branches return output based on narrowed type; execution ends after return.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
xstring | number'hello'3.1415N/A
typeof xN/AstringnumberN/A
OutputN/A'HELLO'N/A'3.14'
Key Moments - 2 Insights
Why can we call toUpperCase() only after checking typeof x === 'string'?
Because before the check, x could be string or number. The typeof check narrows x to string only in that branch, so calling toUpperCase() is safe (see execution_table step 1 and 2).
What happens if we try to call toFixed() without narrowing?
TypeScript would give an error because toFixed() exists only on numbers. Narrowing with typeof ensures we only call it when x is a number (see execution_table step 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when x = 'hello' at step 2?
A'Hello'
B'hello'
C'HELLO'
DError
💡 Hint
Check the Output column at step 2 in execution_table.
At which step does the typeof check fail for x = 3.1415?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Condition and Branch Taken columns for x = 3.1415 in execution_table.
If we remove the typeof check, what would happen when calling toUpperCase() on x?
ATypeScript error because x might be number
BRuntime error only
CIt works fine for all types
DNo output
💡 Hint
Refer to key_moments about calling methods without narrowing.
Concept Snapshot
Type narrowing with typeof:
- Use typeof to check variable type at runtime.
- Narrow union types to specific types inside if branches.
- Safely call methods or operations for narrowed type.
- Example: if(typeof x === 'string') { x.toUpperCase() } else { x.toFixed(2) }
Full Transcript
This visual execution shows how TypeScript uses typeof to narrow variable types. Starting with a variable x that can be string or number, the program checks typeof x. If x is string, it calls toUpperCase(), else it calls toFixed(2) for numbers. The execution table traces each step with input values, conditions, branches taken, and outputs. Variable tracker shows how x and output change. Key moments clarify why narrowing is needed to avoid errors. The quiz tests understanding of output and narrowing steps. This helps beginners see how typeof guides safe code paths.

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

  1. 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).
  2. Step 2: Differentiate from other options

    It does not change, declare, or convert types; it only inspects the type.
  3. Final Answer:

    It checks the type of a variable at runtime. -> Option D
  4. 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

  1. 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'.
  2. 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'.
  3. Final Answer:

    if (typeof value === 'string') { } -> Option A
  4. 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

  1. Step 1: Analyze the input 'hello'

    Since 'hello' is a string, typeof x === 'string' is true, so x.toUpperCase() returns 'HELLO'.
  2. Step 2: Analyze the input 5

    Since 5 is a number, the else block runs, returning 5 + 10 = 15.
  3. Final Answer:

    HELLO and 15 -> Option C
  4. 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

  1. Step 1: Check the type narrowing condition

    The condition typeof value === 'boolean' correctly narrows value to boolean.
  2. Step 2: Identify method call on wrong type

    Inside this block, calling value.toUpperCase() is invalid because booleans do not have this method.
  3. Final Answer:

    Calling toUpperCase on a boolean value -> Option A
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard