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 valueslet bool1:Boolean = falselet bool2:Boolean = true// convert to Numberslet num1 = Number(bool1)let num2 = Number(bool2)// print the numbersconsole.log(num1) // 0console.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.