DEV Community

Cover image for What is control flow based narrowing in TypeScript?
Benny Code for TypeScript TV

Posted on

What is control flow based narrowing in TypeScript?

Control flow based narrowing refers to a type inference technique that allows the TypeScript compiler to narrow down the type of a variable based on the analysis of its control flow within conditional statements (such as if statements and switch statements).

When TypeScript analyzes the control flow of a program, it can determine certain conditions that guarantee the state of a variable. This analysis helps TypeScript to infer a more specific type for that variable within the respective branch of the control flow.

Consider the following TypeScript code snippet:

function processValue(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows here that `value` is of type `string`
    console.log(value.toUpperCase());
  } else {
    // TypeScript knows here that `value` is of type `number`
    console.log(value.toFixed(2));
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, TypeScript uses control flow based narrowing to determine that within the if block, the variable value is a string. Conversely, in the else block, it knows that value is a number.

This enables the compiler to provide more accurate type checking and enables developers to use the appropriate properties or methods specific to each type without explicit type assertions.

Control flow based narrowing is a powerful feature of TypeScript that enhances type safety and helps catch potential errors at compile-time by providing more precise type information based on the analysis of control flow within the code.

Control Flow Based Type Analysis

This video tutorial demonstrates control flow based narrowing:

Interested in learning more? šŸŽ“

I've spent years working with the TypeScript programming language and have encountered its various challenges. That's why I've recorded a series of free TypeScript video tutorials, designed to help you enhancing your coding skills.

I invite you to take a look at them and provide your feedback on the videos. I'm eager to hear your thoughts and impressions. šŸ‘€

Top comments (2)

Collapse
 
johner97 profile image
Johner97

I love TypeScript

Collapse
 
chuksjoe profile image
Chukwunonso Orjiakor

Very precise and detailed. Thanks @bennycode