Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Keywords and Declarations

TypeScript if and else

Reference for if, else if and else in TypeScript: truthiness, how conditions narrow union types, early returns, the ternary operator and common narrowing pitfalls.

if runs a block when its condition is truthy, and else runs another block otherwise. In TypeScript the condition does more than choose a branch: it narrows types. Inside the if block the compiler treats a variable as the more specific type that the test proves, and in the else block as whatever remains.

This is called control-flow narrowing and it works with typeof, instanceof, in, equality, truthiness, discriminant properties and your own type guards.

TypeScript
function len(x: string | string[]) {
  if (typeof x === "string") {
    return x.length;   // x: string
  }
  return x.length;     // x: string[]
}

Try it

TypeScript Narrowing in each branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Truthiness hides zero and empty string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
if (condition) {
  // ...
} else if (other) {
  // ...
} else {
  // ...
}

const result = condition ? a : b;   // conditional expression, narrows too
Part Description
condition Any expression. It is converted to a boolean by JavaScript truthiness rules.
else if Another test, evaluated only if the previous ones were falsy.
else The fallback block.

Falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else is truthy, including "0", [] and {}.

Errors and edge cases:

  • A condition that is always true or false can be flagged: for example, testing a function without calling it in an if is error TS2774 ("This condition will always return true since this function is always defined. Did you mean to call it instead?").
  • Comparing types with no overlap, such as if (x === "a") when x: number, is error TS2367 ("This comparison appears to be unintentional because the types 'number' and 'string' have no overlap").
  • Using if after exhausting a union leaves never in the final else, which you can use for exhaustiveness checks.

Usage notes

  • Prefer early returns. An if (bad) return; followed by the main code narrows the rest of the function without nesting.
  • Truthiness is blunt. if (value) narrows away null and undefined, but also 0, "" and NaN. Compare explicitly when those are valid.
  • Narrowing through aliases. Since TypeScript 4.4, a condition stored in a const (const isStr = typeof x === "string") still narrows x when used in if (isStr).
  • Narrowing is reset by assignments and, for let or properties, by function calls in some cases. Copy to a const when you need stability.
  • No block, no scope. Always use braces; a missing brace is a classic source of bugs, and the dangling else pairs with the nearest if.
  • Ternary (a ? b : c) narrows the same way, and the result type is the union of the two branches.
  • Optional chaining and ?? replace many if (x != null) checks. See the narrowing lesson.