Concept Flow - Control flow analysis behavior
Start
Check Condition
Yes| No
Execute Block
Update State
Repeat or Exit
Control flow analysis checks conditions and tracks variable states to decide which code runs next.
let x: number | undefined; if (Math.random() > 0.5) { x = 10; } if (x !== undefined) { console.log(x + 5); }
| Step | Action | Condition | Variable State | Output |
|---|---|---|---|---|
| 1 | Declare x | N/A | x = undefined | |
| 2 | Evaluate Math.random() > 0.5 | true or false | x = undefined | |
| 3 | If true, assign x = 10 | true | x = 10 | |
| 4 | If false, skip assignment | false | x = undefined | |
| 5 | Check if x !== undefined | depends on x | x = 10 or undefined | |
| 6 | If true, print x + 5 | true | x = 10 | 15 |
| 7 | If false, skip print | false | x = undefined |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| x | undefined | 10 | undefined | 10 or undefined |
Control flow analysis tracks variable states through conditions. It ensures variables are safe to use after checks. Example: assign x conditionally, then use x only if defined. This prevents runtime errors from undefined values. Always check variables before use when types allow undefined.
What does TypeScript's control flow analysis primarily help with?
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());
}typeof value === 'string' narrows value to string inside the if block.value is string here, calling toUpperCase() is safe and valid.toUpperCase() inside the if block -> Option DWhat 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));'hello', the else block runs, returning 'HELLO' after toUpperCase().3.14159, the if block runs, returning '3.14' after toFixed(2).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());
}
}input is null, so calling toLowerCase() causes a runtime error.input in the if block but not in else, so unsafe call happens.toLowerCase() on null in the else block causes a runtime error -> Option AGiven 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();
}return input.trim() runs when input is null, causing an error.if (input !== null) before calling trim() prevents errors.return to avoid calling trim() on null -> Option APass the test and this pattern moves unknown