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.
Declaring 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 the comparison between 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"