Open In App

TypeScript Control Flow Analysis

In this article, we are going to learn about Control flow analysis in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. Control flow analysis in TypeScript refers to the process by which the TypeScript compiler analyzes the flow of your code and makes inferences about the types of variables at different points in your program.

Usage of Control Flow Analysis

Example 1: In this example, TypeScript uses control flow analysis to narrow the type of the value variable within each if and else if block based on the type guards (typeof). This enables safe and accurate type-checking within each code block.






function processValue(value: string | number | null) {
    if (typeof value === 'string') {
      
        // Inside this block, 'value'
        //   is narrowed to 'string'
        console.log(value.toUpperCase());
    } else if (typeof value === 'number') {
      
        // Inside this block, 'value'
        // is narrowed to 'number'
        console.log(value.toFixed(2));
    } else {
          
        // Inside this block, 'value'
        // is narrowed to 'null'
        console.log('Value is null or not a string/number');
    }
}
  
processValue('Hello');
processValue(42);
processValue(null);

Output:

Example 2: In this example, the processData function takes an argument data that can be of type string, number, or boolean. TypeScript uses control flow analysis to narrow the type of data within each conditional branch. When data is determined to be a string, the code inside the first if block operates on it as a string. similarly it will check for number and boolean.






function processData(data: string | number | boolean) {
    if (typeof data === 'string') {
      
        // Inside this block, 'data' 
        //is narrowed to 'string'
        console.log(`Length of the string: ${data.length}`);
    } else if (typeof data === 'number') {
          
        // Inside this block, 'data' 
        // is narrowed to 'number'
        if (data > 0) {
            console.log(`Square of the number: ${data * data}`);
        } else {
            console.log('The number is not positive.');
        }
    } else {
          
        // Inside this block, 'data' 
        // is narrowed to 'boolean'
        if (data) {
            console.log('The boolean value is true.');
        } else {
            console.log('The boolean value is false.');
        }
    }
}
  
processData('Hello');
processData(3);
processData(false);

Output:


Article Tags :