How to convert a boolean to a number in TypeScript

Overview

The Number() method explicitly converts a boolean to a number. In this shot, we learn to convert a boolean value to a number.

Syntax

Number(booleanValue)
The syntax to convert a boolean to a number in JavaScript

Parameters

booleanValue: This is the boolean value we want to convert to a number.

Return value

A number is returned.

Example

// create some boolean values
let bool1:Boolean = false
let bool2:Boolean = true
// convert to Numbers
let num1 = Number(bool1)
let num2 = Number(bool2)
// print the numbers
console.log(num1) // 0
console.log(num2) // 1

Explanation

  • Lines 2 and 3: We create some boolean values in TypeScript.
  • Lines 6 and 7: We convert the boolean values to numeric values using the Number() method. Then, we save the results.
  • Lines 10 and 11: We print the results to the console.

Free Resources