QA
Senior LevelJavaScript & TypeScript

How does TypeScript's type checker engine perform type inference and control flow analysis?

❓ Interview Prompt: Explain Control Flow Analysis (CFA), reachability analysis, assertion effects, and type narrowing graphs.

TypeScript's Control Flow Analysis (CFA) is the flow-sensitive mechanism that evaluates statements, assignments, and expressions sequentially to narrow types dynamically across code execution paths.

CFA Mechanics:

1
Creates a Control Flow Graph tracking branches (if, switch), loops (for, while), and early returns (return, throw).
2
Evaluates type assertions and assignments along each execution branch.
3
Reachability Analysis: Automatically identifies unreachable code and marks return types as never.

Code Implementation Example

typescript
function analyzeFlow(val: string | number | null) {
  if (val === null) return; // CFA eliminates 'null' for remainder of function!
  
  // val is now 'string | number'
  if (typeof val === 'string') {
    console.log(val.length); // CFA narrows val to 'string'
    return;
  }
  
  // CFA knows val MUST be 'number' here! (Early return executed above)
  console.log(val.toFixed(2));
}
💡Control Flow Analysis eliminating types sequentially using early returns and guard clauses.
🎯 Interview Key Takeaway

Control Flow Analysis evaluates execution graphs to eliminate types sequentially after guard clauses and early returns.

#TypeScript#CFA#Control Flow#Engine#Senior
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?