0
0
Typescriptprogramming~5 mins

Boolean type behavior in Typescript

Choose your learning style9 modes available
Introduction

Booleans help us decide between two choices: true or false. They make programs smart by checking conditions.

Checking if a user is logged in or not
Deciding if a light switch is on or off
Verifying if a password is correct
Controlling if a button should be clickable
Determining if a number is positive or negative
Syntax
Typescript
let isDone: boolean = true;

// or

let isOpen: boolean;
isOpen = false;

Boolean values can only be true or false.

Use boolean type to tell TypeScript this variable holds true/false.

Examples
This sets isSunny to true and prints it.
Typescript
let isSunny: boolean = true;
console.log(isSunny);
Declare first, assign later, then print false.
Typescript
let hasAccess: boolean;
hasAccess = false;
console.log(hasAccess);
Boolean can come from comparisons like 5 > 3, which is true.
Typescript
let isAdult: boolean = 5 > 3;
console.log(isAdult);
Sample Program

This program checks if a person can drive based on age. It returns true if age is 18 or more, false otherwise.

Typescript
function canDrive(age: number): boolean {
  return age >= 18;
}

const age1 = 20;
const age2 = 16;

console.log(`Age ${age1} can drive:`, canDrive(age1));
console.log(`Age ${age2} can drive:`, canDrive(age2));
OutputSuccess
Important Notes

Boolean values are often the result of comparisons or logical operations.

Never assign numbers or strings directly to a boolean variable without conversion.

Use booleans to control program flow with if statements or loops.

Summary

Booleans hold only two values: true or false.

They help programs make decisions.

Use boolean type in TypeScript to ensure correct true/false values.