0
0
Typescriptprogramming~10 mins

Why type narrowing is needed in Typescript - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why type narrowing is needed
Start: variable with union type
Check type with condition
Use narrowed type
End
We start with a variable that can be multiple types. We check its type using a condition. If the check passes, we safely use the variable as the narrowed type. Otherwise, we handle the other type.
Execution Sample
Typescript
function printLength(x: string | number) {
  if (typeof x === 'string') {
    console.log(x.length);
  } else {
    console.log(x.toFixed(2));
  }
}
This function checks if x is a string or number, then safely uses string or number methods accordingly.
Execution Table
StepVariable xConditionCondition ResultActionOutput
1'hello'typeof x === 'string'trueUse x.length5
242typeof x === 'string'falseUse x.toFixed(2)42.00
3truetypeof x === 'string'falseError (not string or number)Error (not number)
💡 Execution stops after handling all cases or error if type is unexpected
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
xstring | number | booleanstringnumberboolean
Key Moments - 2 Insights
Why can't we call x.length directly without checking the type?
Because x can be a number or string, and numbers don't have length. The execution_table row 2 shows that if x is a number, calling length would cause an error.
What happens if we don't handle the else case?
If we skip the else, the code might try to use string methods on numbers or vice versa, causing runtime errors. The execution_table row 3 shows an error when type is unexpected.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when x is 'hello' at step 1?
A42.00
BError
C5
Dundefined
💡 Hint
Check the Output column in row 1 of execution_table
At which step does the condition typeof x === 'string' evaluate to false?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at the Condition Result column in execution_table rows 2 and 3
If we remove the else block, what will happen when x is 42?
AIt will print 42.00
BIt will do nothing
CIt will cause a runtime error
DIt will print 2
💡 Hint
Without else, the number case is not handled, so no output occurs for x=42
Concept Snapshot
Type narrowing lets TypeScript know the exact type inside a condition.
Use conditions like typeof or instanceof to check types.
Inside the true branch, you can safely use methods of the narrowed type.
Without narrowing, TypeScript warns about unsafe operations.
Narrowing prevents runtime errors by ensuring correct type usage.
Full Transcript
Type narrowing is needed because variables can have multiple types, called union types. When you want to use a method or property specific to one type, you must first check the variable's type. For example, a variable x can be a string or number. Strings have a length property, but numbers do not. So, before calling x.length, you check if x is a string using typeof x === 'string'. If true, you safely use x.length. Otherwise, you handle the number case, like calling x.toFixed(2). This prevents errors and helps TypeScript understand your code better.