How to convert a Value to a Boolean in TypeScript

avatar

Borislav Hadzhiev

Sun Feb 20 20222 min read

Convert a Value to a Boolean in TypeScript #

Use the Boolean object to convert a value to a boolean in Typescript, e.g. Boolean(someValue). When used as a function, the Boolean object converts the passed in value to a boolean - true if the value is truthy and false if it's a falsy value.

index.ts
const str1 = 'hello'; // 👇️ const bool1: boolean const bool1 = Boolean(str1); console.log(bool1); // 👉️ true

We used the Boolean object to convert a value to a boolean.

The boolean object returns false if the passed in value is falsy.

The falsy values in JavaScript are: false, 0, "" (empty string), null, undefined, NaN (not a number).

In all other cases, true is returned.

Here are some examples of using the Boolean object.

index.ts
console.log(Boolean([])); // 👉️ true console.log(Boolean({})); // 👉️ true console.log(Boolean('')); // 👉️ false console.log(Boolean('false')); // 👉️ true console.log(Boolean(0)); // 👉️ false console.log(Boolean(10)); // 👉️ true

Note that an empty array and empty object are truthy values, whereas an empty string is falsy.

An alternative approach, but also very common approach is to use the double bang (!!) operator.
index.ts
// 👇️ const bool1: true const bool1 = !!'hello'; console.log(bool1); // 👉️ true // 👇️ const bool1: false const bool2 = !!''; console.log(bool2); // 👉️ false

Using the double bang (!!) operator is the same as using the logical NOT (!) operator twice.

The logical NOT (!) operator converts a value into a boolean and inverts the result.

index.js
console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true

When we use the logical NOT (!) operator twice, we:

  • convert the value to a boolean and flip it
  • flip the boolean again

An easy way to think about it is - we're basically converting a value to a boolean.

Here are some examples.

index.js
console.log(!![]); // 👉️ true console.log(!!{}); // 👉️ true console.log(!!''); // 👉️ false console.log(!!'false'); // 👉️ true console.log(!!0); // 👉️ false console.log(!!10); // 👉️ true
Most of the time it's better to be explicit and use the Boolean object, especially when working with developers who might not be familiar with the double NOT (!!) operator.
Use the search field on my Home Page to filter through my more than 1,000 articles.