What does the boolean type do?
What the boolean type does in TypeScript
The boolean type in TypeScript represents a logical value that can be only one of two:
true or false.
It is used to express logical states, for example "on / off", "active / inactive", "logged in / not", and so on.
How to declare a variable of type boolean
1. Explicit type annotation
javascript
let isOnline: boolean = true;
let hasAccess: boolean = false;2. Implicit determination (type inference)
TypeScript automatically infers the type:
javascript
let isActive = true; // type: booleanUsage examples
javascript
let isAdmin: boolean = true;
let isLoggedIn: boolean = false;
// Use in conditions:
if (isAdmin) {
console.log("Welcome, administrator!");
} else {
console.log("Access restricted.");
}
// Assignment based on an expression:
let hasPermission: boolean = 5 > 2; // trueConversion to boolean
TypeScript (and JavaScript) automatically coerces values to a logical type in conditions. Here are examples of which values are considered falsy and truthy:
Falsy values (coerce to false) | Truthy values (coerce to true) |
|---|---|
false | true |
0, -0 | Any nonzero number |
"" (empty string) | "text" |
null | {}, [] |
undefined | Any non-empty value |
NaN |
Example:
javascript
let value = "";
let isEmpty = Boolean(value); // falseImportant
-
Use
boolean, not theBooleanobject:javascriptlet flag: boolean = true; // primitive let badFlag: Boolean = new Boolean(true); // object, not recommended
The Boolean object is always considered truthy, even if it wraps false:
javascript
if (new Boolean(false)) {
console.log("This will run!");
}Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.