Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The else clause is a fundamental control flow construct that dictates the execution path when its associated if condition evaluates to a falsy value. In TypeScript, the else block is integral to control flow analysis; the compiler automatically applies the logical complement of any type guards evaluated in the preceding if statement to narrow types within the else scope.

Syntax

The else clause must immediately follow an if block or an else if block.
if (condition) {
  // Statements executed if condition is truthy
} else {
  // Statements executed if condition is falsy
}

Control Flow Analysis and Type Narrowing

TypeScript’s type checker performs static analysis on if/else statements. When a union type is evaluated using a type guard (such as typeof, instanceof, or custom type predicates) in the if condition, TypeScript narrows the type in the if block and assigns the remaining constituent types to the else block.
function process(value: string | number | boolean) {
  if (typeof value === "string") {
    // Type of 'value' is narrowed to 'string'
  } else {
    // Type of 'value' is narrowed to 'number | boolean'
  }
}

Chaining with else if

Multiple conditions can be evaluated sequentially by chaining an if statement directly onto an else clause. TypeScript continues to narrow the type down the chain by subtracting the types matched in previous conditions.
function evaluate(value: string | number | boolean) {
  if (typeof value === "string") {
    // 'value' is 'string'
  } else if (typeof value === "number") {
    // 'value' is 'number'
  } else {
    // 'value' is strictly narrowed to 'boolean'
  }
}

Exhaustiveness Checking

In strict TypeScript configurations, the else clause is frequently utilized to enforce exhaustiveness checking on union types. By assigning the narrowed value to a variable of type never inside the final else block, the compiler will throw an error if the union is modified in the future without a corresponding condition being added to the control flow.
type State = "idle" | "loading" | "success";

function handleState(state: State) {
  if (state === "idle") {
    // state is "idle"
  } else if (state === "loading") {
    // state is "loading"
  } else if (state === "success") {
    // state is "success"
  } else {
    // state is narrowed to 'never'
    // This assignment will cause a compile-time error if a new State is added
    const _exhaustiveCheck: never = state; 
  }
}
Master TypeScript with Deep Grasping Methodology!Learn More