liveBook · Manning

Boolean

As explained in Essential TypeScript 5, Third Edition

The boolean type is the JavaScript and TypeScript type whose values are true or false.

A boolean represents one of two values: true or false. JavaScript infers boolean values from assignments, while TypeScript can use boolean assertions and checks to describe them. section 7.2 section 7.4.1

Observing a boolean value

let myVar;\nconsole.log(`${myVar} = ${typeof myVar}`);\nmyVar = true;\nconsole.log(`${myVar} = ${typeof myVar}`);\n\n// undefined = undefined\n// true = boolean

Boolean behavior matters when JavaScript compares or combines values. Strict equality (===) compares both type and value, whereas logical OR (||) converts several values to false and may select a fallback. section 3.3.2

Treat fallback expressions carefully:

  • Use || when values such as null or undefined should trigger a fallback, but remember that false, 0, an empty string, and NaN also trigger it. section 3.3.2
  • Do not confuse a TypeScript assertion with conversion: asserting a string | number result as boolean changes checking only, not the runtime value. section 7.4.1

An unsafe boolean assertion

function calculateTax(amount: number, format: boolean): string | number {\n const calcAmount = amount * 1.2;\n return format ? `$${calcAmount.toFixed(2)}` : calcAmount;\n}\n\nlet taxBoolean = calculateTax(100, false) as any as boolean;\nconsole.log(taxBoolean); // 120

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains definition, inference, coercion, fallback operators, and assertion limits, but stops short of deeper boolean implementation details.
Examples
Demonstrates typeof output, price comparison, fallback tax rates, nullish coalescing, and an unsafe calculateTax assertion.
What it assumes
Assumes familiarity with JavaScript variables, functions, operators, and TypeScript compilation while defining boolean values from examples.
What you can do after
Apply via JavaScript operators and TypeScript assertions while recognizing when runtime values do not match declared boolean types.
How it connects
Connects booleans with JavaScript type coercion, strict equality, nullish coalescing, TypeScript union types, and type assertions.

Also explained in

Compare how 11 books explain boolean →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.