Skip to main content

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: boolean

Usage 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; // true

Conversion 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)
falsetrue
0, -0Any nonzero number
"" (empty string)"text"
null{}, []
undefinedAny non-empty value
NaN

Example:

javascript
let value = ""; let isEmpty = Boolean(value); // false

Important

  • Use boolean, not the Boolean object:

    javascript
    let 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.