Typescript boolean
Created By: chatGPT
TypeScript provides a primitive type called
boolean
, which represents one of two values: true
or false
. This type is commonly used in conditional statements, loops, and expressions.// Example of boolean usage in TypeScript
let isTypeScriptFun: boolean = true;
if (isTypeScriptFun) {
console.log('TypeScript is fun!');
} else {
console.log('TypeScript is not fun.');
}
Boolean values can also be derived from expressions. For instance, comparison operators like
>
, <
, ===
, and !==
will return a boolean result.// Using comparison operators to produce boolean values
let a: number = 5;
let b: number = 10;
let isEqual: boolean = (a === b); // false
let isGreater: boolean = (a > b); // false
let isLess: boolean = (a < b); // true
console.log(`Is a equal to b? ${isEqual}`);
console.log(`Is a greater than b? ${isGreater}`);
console.log(`Is a less than b? ${isLess}`);
TypeScript also allows you to use boolean values in logical expressions with the logical operators:
&&
(AND), ||
(OR), and !
(NOT).// Logical operators with boolean values
let condition1: boolean = true;
let condition2: boolean = false;
let resultAND: boolean = condition1 && condition2; // false
let resultOR: boolean = condition1 || condition2; // true
let resultNOT: boolean = !condition1; // false
console.log(`Result of AND: ${resultAND}`);
console.log(`Result of OR: ${resultOR}`);
console.log(`Result of NOT: ${resultNOT}`);
It's important to note that TypeScript allows boolean values to be used with non-boolean values in a way that still adheres to boolean logic in conditions. Non-zero numbers, non-empty strings, and objects are considered truthy, while zero, undefined, null, or empty strings are considered falsy.
// Truthy and falsy examples
let truthyValue: number = 1; // truthy
let falsyValue: number = 0; // falsy
if (truthyValue) {
console.log('This is truthy!');
}
if (!falsyValue) {
console.log('This is falsy!');
}