Lesson 20 of 55
15 mins readPython Type Narrowing with typeof and Truthiness
In Plain English
Control flow analysis allows TypeScript to narrow union types within conditional branches based on standard JavaScript runtime operators like typeof.
Core Rules to Remember

Control Flow Analysis: TypeScript inspects conditional branches to narrow variable types automatically.

typeof Guards: typeof x === "string" narrows x to string in the branch.
Live Interactive Example
Hit Run Code to see it liveNarrowing Primitive Unions
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: val is narrowed to string in the if branch and number in the else branch.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Calculate Length or Magnitude
Write function getDimension(input: string | number[] | number): number.
If typeof input is "number", return input.
If typeof input is "string" or Array.isArray(input), return input.length.
Test with "TypeScript" and print the result.
1
2
3
4
5
6
7
8
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.