Control flow analysis helps TypeScript understand how your code runs step-by-step. It checks what values variables can have at different points, so it can catch mistakes early.
Control flow analysis behavior in Typescript
if (condition) { // code when condition is true } else { // code when condition is false }
TypeScript uses control flow to check variable types inside these blocks.
It narrows types based on conditions, like checking if a variable is not null.
value is a string, not null.let value: string | null = "hello"; if (value !== null) { console.log(value.toUpperCase()); }
x to string or number inside each block.function printLength(x: string | number) { if (typeof x === "string") { console.log(x.length); } else { console.log(x.toFixed(2)); } }
count is a number inside the if because undefined is excluded.let count: number | undefined; count = 5; if (count !== undefined) { console.log(count + 1); }
This program uses control flow to check if name has a value. If yes, it prints a greeting with the name in uppercase. Otherwise, it prints a generic greeting.
function greet(name: string | null) { if (name) { console.log(`Hello, ${name.toUpperCase()}!`); } else { console.log("Hello, stranger!"); } } greet("Alice"); greet(null);
Control flow analysis helps avoid errors by understanding variable states.
It works best with simple conditions like if, else, and typeof checks.
Complex code might confuse control flow, so keep conditions clear and simple.
Control flow analysis tracks how your code runs to check variable types.
It helps TypeScript catch errors before running your program.
Use conditions to let TypeScript narrow variable types safely.
Practice
What does TypeScript's control flow analysis primarily help with?
Solution
Step 1: Understand control flow analysis purpose
Control flow analysis tracks how variables change types through different code paths.Step 2: Identify its main benefit
This helps TypeScript catch type errors before running the program.Final Answer:
Tracking variable types through code paths to catch errors early -> Option BQuick Check:
Control flow analysis = type tracking [OK]
- Confusing control flow analysis with code execution speed
- Thinking it fixes syntax errors automatically
- Believing it compiles TypeScript to JavaScript
Which of the following TypeScript code snippets correctly narrows a variable's type using control flow analysis?
let value: string | number = 5;
if (typeof value === 'string') {
console.log(value.toUpperCase());
}Solution
Step 1: Check the type guard condition
The conditiontypeof value === 'string'narrowsvalueto string inside the if block.Step 2: Confirm safe method call
Sincevalueis string here, callingtoUpperCase()is safe and valid.Final Answer:
The code is correct and safe to calltoUpperCase()inside the if block -> Option DQuick Check:
Type guard narrows type = safe method call [OK]
- Calling string methods without type narrowing
- Confusing typeof with instanceof for primitives
- Assuming type assertions are always needed
What will be the output of this TypeScript code?
function checkValue(x: string | number) {
if (typeof x === 'number') {
return x.toFixed(2);
} else {
return x.toUpperCase();
}
}
console.log(checkValue('hello'));
console.log(checkValue(3.14159));Solution
Step 1: Analyze the first call with string
For'hello', the else block runs, returning'HELLO'aftertoUpperCase().Step 2: Analyze the second call with number
For3.14159, the if block runs, returning'3.14'aftertoFixed(2).Final Answer:
"HELLO" and "3.14" -> Option CQuick Check:
Type guards produce correct string outputs [OK]
- Assuming toFixed returns a number, not string
- Ignoring type narrowing in if-else
- Mixing up output formatting
Identify the error in this TypeScript code related to control flow analysis:
function process(input: string | null) {
if (input) {
console.log(input.toLowerCase());
} else {
console.log(input.toLowerCase());
}
}Solution
Step 1: Check the else block usage
In the else block,inputisnull, so callingtoLowerCase()causes a runtime error.Step 2: Understand control flow limitation
Control flow analysis narrowsinputin the if block but not in else, so unsafe call happens.Final Answer:
CallingtoLowerCase()onnullin the else block causes a runtime error -> Option AQuick Check:
Null check needed before method call [OK]
- Assuming if(input) excludes null everywhere
- Expecting TypeScript to fix runtime errors
- Using loose null checks without safe calls
Given this TypeScript code, what is the best way to fix the control flow analysis issue to avoid errors?
function formatInput(input: string | number | null) {
if (typeof input === 'string') {
return input.trim();
} else if (typeof input === 'number') {
return input.toFixed(1);
}
return input.trim();
}Solution
Step 1: Identify the problem with last return
The lastreturn input.trim()runs wheninputisnull, causing an error.Step 2: Fix by adding null check
Adding a check likeif (input !== null)before callingtrim()prevents errors.Final Answer:
Add a null check before the lastreturnto avoid callingtrim()on null -> Option AQuick Check:
Null checks prevent unsafe method calls [OK]
- Ignoring null possibility in union types
- Assuming last return is unreachable
- Using type assertions without safety
Ready to prove it?
Pass the test and this pattern moves unknown
