TypeScript Boolean

TypeScript is a superset of JavaScript that provides optional static typing, making it easier to write complex code. One of the basic data types that TypeScript provides is the Boolean data type. In this lesson, we will go over what TypeScript Booleans are, how they work, and how to use them with code examples.

What is a Boolean in TypeScript?

In TypeScript, a Boolean is a data type that represents a logical value of either true or false. A Boolean is used to make decisions in code by evaluating conditions.

You can declare a Boolean variable using the following syntax:

let isDone: boolean = false;

In this example, we create a variable called isDone of type boolean and set its initial value to false.

You can also use the Boolean() function to create a Boolean value:

let isWorking: boolean = Boolean(1);

In this example, we create a variable called isWorking of type boolean and set its initial value to true because the argument passed to the Boolean() function (1) is considered truthy.

How to Use a Boolean in TypeScript

Once you have defined a Boolean variable, you can use it in your code like this:

let isDone: boolean = false;
if (isDone) {
  console.log('Task is done');
} else {
  console.log('Task is not done');
}

In this example, we declare a variable called isDone and set its initial value to false. We then use an if statement to check whether isDone is true or false. If it is true, we print ‘Task is done’ to the console. If it is false, we print ‘Task is not done’ to the console.

You can also use Boolean operators like && (and), || (or), and ! (not) to create more complex conditions:

let isRaining: boolean = true;
let isCold: boolean = false;

if (isRaining && !isCold) {
  console.log('Take an umbrella');
} else if (isRaining && isCold) {
  console.log('Take an umbrella and a coat');
} else {
  console.log('Enjoy the weather');
}

In this example, we declare two Boolean variables called isRaining and isCold. We use the && operator (and) and the ! operator (not) to create a condition that checks whether it is raining but not cold. If it is, we print ‘Take an umbrella’ to the console. We use the || operator (or) to create a condition that checks whether it is both raining and cold. If it is, we print ‘Take an umbrella and a coat’ to the console. Finally, if none of the conditions are met, we print ‘Enjoy the weather’ to the console.

Conclusion

In conclusion, Booleans are a simple but important feature of TypeScript that are used to make decisions in code. They help make your code more readable, maintainable, and less error-prone. With Booleans, you can evaluate conditions and perform actions based on those conditions.