Boolean values are fundamental in programming, representing true or false states that help control the flow of logic in code. TypeScript provides strong support for booleans, ensuring that you can confidently use them to make your applications more predictable and error-free. In this tutorial, we’ll explore how booleans work in TypeScript, starting from the basics and progressing to advanced applications.
The boolean type in TypeScript represents two values: true
and false
. These values are essential for decision-making, allowing you to control the flow of your program by checking conditions, validating states, and making logical choices. TypeScript enhances the boolean type by enforcing strict type-checking, which reduces errors and helps you write cleaner code.
A boolean in TypeScript is a data type that can hold one of two values: true
or false
. This type is often used to represent on/off states, yes/no answers, and other binary conditions.
let isCompleted: boolean = true;
let isLoggedIn: boolean = false;
In the example above, isCompleted
and isLoggedIn
are both boolean variables, and TypeScript will ensure that they can only hold true
or false
values.
In TypeScript, you can declare boolean variables using either explicit type annotations or type inference.
A boolean literal in TypeScript is simply the true
or false
value itself. You can assign these literals to variables with or without an explicit type annotation.
let isAvailable: boolean = true;
let isMember: boolean = false;
With explicit annotations, TypeScript ensures that the values of isAvailable
and isMember
are always booleans.
TypeScript can infer the type of a boolean variable based on the assigned value, so you can skip the explicit type annotation if it’s clear from context.
let isActive = true; // Inferred as boolean
let hasAccess = false; // Inferred as boolean
In this example, TypeScript infers that isActive
and hasAccess
are booleans based on the assigned literals, making the code more concise.
Boolean expressions are conditions or comparisons that evaluate to either true
or false
. TypeScript supports several operators to create these expressions.
Comparison operators include:
===
: Strict equality!==
: Strict inequality>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal tolet age = 20;
let isAdult = age >= 18; // Evaluates to true
Logical operators are used to combine multiple boolean expressions.
&&
(AND): Returns true
only if both expressions are true
.||
(OR): Returns true
if at least one of the expressions is true
.!
(NOT): Returns the opposite boolean value.let isVerified = true;
let isSubscribed = false;
let canAccessContent = isVerified && isSubscribed; // false
let canViewPreview = isVerified || isSubscribed; // true
let cannotAccessContent = !canAccessContent; // true
In this example:
canAccessContent
is false
because both conditions must be true
.canViewPreview
is true
because at least one condition is true
.cannotAccessContent
negates canAccessContent
, so it’s true
.Boolean values are commonly used in conditional statements to control the flow of logic.
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
In this example, the if statement checks the value of isLoggedIn
. If isLoggedIn
is true
, the message “Welcome back!”
is displayed; otherwise, “Please log in”
is shown.
Boolean functions return a boolean value based on certain conditions. These functions are useful for encapsulating logic that determines a true
/false
state.
function isEligibleForDiscount(age: number): boolean {
return age >= 65;
}
let discountEligibility = isEligibleForDiscount(70); // true
Here, isEligibleForDiscount
takes age as a parameter and returns true if the age is 65 or above.
Boolean logic with AND, OR, and NOT operators is essential for creating complex conditions. TypeScript supports these logical operators, which can combine multiple boolean expressions in a single statement.
let isMember = true;
let hasCoupon = false;
let discountEligibility = isMember || hasCoupon && !hasCoupon;
console.log(discountEligibility); // true
In this example:
||
) evaluates to true because isMember
is true
.!
) reverses the value of hasCoupon
.In a web application, booleans are often used to check whether a user is authenticated and authorized to access certain features.
let isAuthenticated = true;
let isAdmin = false;
function accessDashboard(): void {
if (isAuthenticated && isAdmin) {
console.log("Access granted to admin dashboard.");
} else if (isAuthenticated) {
console.log("Access granted to user dashboard.");
} else {
console.log("Please log in to continue.");
}
}
accessDashboard(); // Outputs: "Access granted to user dashboard."
This example checks two boolean values:
isAuthenticated
: Indicates whether the user is logged in.isAdmin
: Indicates whether the user has admin privileges.The accessDashboard
function uses these booleans to determine which part of the dashboard the user can access.
Booleans are commonly used in form validation, where each field may have a validation status.
let isNameValid = true;
let isEmailValid = false;
let isFormValid = isNameValid && isEmailValid;
function submitForm() {
if (isFormValid) {
console.log("Form submitted successfully!");
} else {
console.log("Please fill out all required fields.");
}
}
submitForm(); // Outputs: "Please fill out all required fields."
In this case, isFormValid
is set to true
only if both isNameValid
and isEmailValid
are true
. This simple validation logic helps prevent form submission if any required field is invalid.
true
and false
.&&
), OR (||
), and NOT (!
) allow you to combine and manipulate boolean expressions.TypeScript’s boolean types are simple yet incredibly powerful. From managing conditional logic to building complex expressions, booleans are essential for controlling the flow of your program. This guide covered the basics of boolean types, how to declare and use them, and real-world examples that illustrate their practical applications. By understanding how to work with booleans in TypeScript, you can write code that is cleaner, more reliable, and easier to maintain.