Language: EN

typescript-tipos-boolean

The Boolean Type in TypeScript

In TypeScript, the boolean type represents one of two values: true or false. These values are commonly used to control the flow of the program, perform comparisons, and express conditions.

The declaration of boolean variables in TypeScript is done by specifying the boolean type and assigning a value of true or false.

let isActive: boolean = true;
let isAuthenticated: boolean = false;

Boolean operators

Comparison operators

Comparison operators return a boolean value as a result of comparing two values.

  • == (equality) and === (strict equality)
  • != (inequality) and !== (strict inequality)
  • <, <=, >, >=
let x: number = 10;
let y: number = 20;

console.log(x == y);  // false
console.log(x != y);  // true
console.log(x < y);   // true
console.log(x >= y);  // false

Logical operators

TypeScript supports common logical operators to work with boolean values.

  • && (logical AND): Returns true if both operands are true.
let a: boolean = true;
let b: boolean = false;
console.log(a && b);  // false
  • || (logical OR): Returns true if at least one of the operands is true.
console.log(a || b);  // true
  • ! (logical NOT): Inverts the boolean value.
console.log(!a);  // false
console.log(!b);  // true

Type conversion

From values to booleans

JavaScript (and by extension TypeScript) has concepts of truthy and falsy values. These values are implicitly converted to booleans in boolean contexts.

Common falsy values include:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy.

console.log(Boolean(0));         // false
console.log(Boolean(""));        // false
console.log(Boolean("Hello"));   // true
console.log(Boolean(123));       // true

From booleans to values

Booleans can be converted to other data types, although this is not a common practice.

let trueValue: boolean = true;
let falseValue: boolean = false;

console.log(Number(trueValue));  // 1
console.log(Number(falseValue));  // 0
console.log(String(trueValue));  // "true"
console.log(String(falseValue));  // "false"