Convert a Boolean to a Number in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 20, 2022

banner

Photo from Unsplash

Convert a Boolean to a Number in TypeScript #

Use the Number object to convert a boolean to a number in TypeScript, e.g. const num = Number(true). When used as a function, Number(value) converts a value to a number. If the value cannot be converted, it returns NaN (not a number).

index.ts
const bool1 = true; // 👇️ const num1: number const num1 = Number(bool1); console.log(num1); // 👉️ 1 const bool2 = false; // 👇️ const num2: number const num2 = Number(bool2); console.log(num2); // 👉️ 0

We used the Number function to convert a boolea to a number.

The only parameter we passed to the function is the value we want to convert to a number.

Booleans with a value of true get converted to 1 and false values get converted to 0.

You might also see developers use the unary plus (+) operator to convert a boolean to a number.

index.ts
const bool1 = true; // 👇️ const num1: number const num1 = +bool1; console.log(num1); // 👉️ 1 const bool2 = false; // 👇️ const num2: number const num2 = +bool2; console.log(num2); // 👉️ 0

It achieves the same goal as the Number function, but might be confusing to readers of your code who are not familiar with the unary plus (+) operator.

You should avoid using the unary plus (+) operator when adding numbers, because it makes your code look quite strange.

index.ts
const bool1 = true; const bool2 = false; const sum = +bool1 + +bool2; console.log(sum); // 👉️ 1

The second plus is the addition operator and the other ones are used to convert the boolean values to numbers.

Both approaches have correct typing and allow TypeScript to infer that the variable stores a number.

Which approach you pick is a matter of personal preference. I'd go with using the Number() function as it's more explicit and makes your code easier to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.