Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

The TypeScript boolean type

Reference for the boolean type in TypeScript: true and false, the union behind it, truthiness, Boolean(), narrowing with conditions and boolean flags.

boolean has exactly two values: true and false. Internally TypeScript treats it as the union true | false, which is why narrowing on a boolean property of a discriminated union works and why boolean can be split in a switch.

Conditions in if, while, the ternary and &&/|| accept any value, not only booleans. Values are converted by the truthiness rules, and TypeScript narrows according to them.

TypeScript
let isReady: boolean = false;
const hasItems = [1, 2].length > 0; // inferred: boolean

Try it

TypeScript Truthiness and Boolean()

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 Booleans as unions

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
let flag: boolean = true;
type Literal = true;        // the type containing only true
const result = !!value;     // coerce to boolean
Form Description
Boolean(x) Converts any value using the truthiness rules and returns a primitive boolean.
!x, !!x Negation and double negation (coercion).
x && y, x || y Short-circuit operators; they return one of the operands, not necessarily a boolean.
new Boolean(x) Creates a wrapper object. Never use it: an object is always truthy.

Usage notes

  • Falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including [], {} and "0", is truthy.
  • && and || do not return booleans. "a" && 5 is 5. Use Boolean() when you need a real flag.
  • Narrowing. Truthiness checks remove null, undefined, 0, "" and false from a type. Be careful with numbers and strings: if (count) also rejects 0. Prefer count !== undefined.
  • Negations on unions. if (!flag) narrows flag to false when it is boolean.
  • Names. Start boolean names with is, has, can or should.
  • Many flags are a design smell. Several booleans can describe impossible combinations; a discriminated union or a string literal union is safer.
  • Optional booleans have three states (true, false, undefined); be explicit about what undefined means.
  • Strict comparisons. flag === true is rarely needed and defeats narrowing from truthy values only when flag is not already boolean.