The boolean Type
What You'll Learn: How TypeScript represents true/false values with the boolean type.
What Is a Boolean?
In TypeScript (and most programming languages), a boolean is a data type that can only hold one of two values: true or false. Think of it like a light switch — it's either on or off, with no in-between state.
The boolean type is fundamental for making decisions in your code. It answers yes-or-no questions: Is the user logged in? Has the form been submitted? Is this number greater than 10?
Declaring Boolean Variables
When you want to tell TypeScript that a variable will hold a true/false value, you use the boolean type annotation:
let isActive: boolean = true;
let hasErrors: boolean = false;
TypeScript can also infer the boolean type automatically if you initialize the variable with true or false:
let isComplete = true; // TypeScript knows this is a boolean
Why It Matters
By declaring something as a boolean, TypeScript ensures you can only assign true or false to that variable. If you accidentally try to assign a number, string, or other value, TypeScript will catch that error before your code runs.
This prevents common bugs where you might confuse a boolean flag with other values.
Key Takeaway: The boolean type in TypeScript represents true/false values and helps ensure your logic flags stay strictly binary, catching errors when non-boolean values are accidentally used.