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.
let isReady: boolean = false; const hasItems = [1, 2].length > 0; // inferred: boolean
Try it
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.
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
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,undefinedandNaN. Everything else, including[],{}and"0", is truthy. &&and||do not return booleans."a" && 5is5. UseBoolean()when you need a real flag.- Narrowing. Truthiness checks remove
null,undefined,0,""andfalsefrom a type. Be careful with numbers and strings:if (count)also rejects0. Prefercount !== undefined. - Negations on unions.
if (!flag)narrowsflagtofalsewhen it isboolean. - Names. Start boolean names with
is,has,canorshould. - 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 whatundefinedmeans. - Strict comparisons.
flag === trueis rarely needed and defeats narrowing from truthy values only whenflagis not alreadyboolean.