Borislav Hadzhiev
Sat Feb 19 2022·2 min read
Photo by Chermiti Mohamed
Use the String
object to convert a boolean to a string in TypeScript, e.g.
const str = String(bool)
. When used as a function, the String
object
converts the passed in value to a string
and returns the result.
// 👇️ const bool: true const bool = true; // 👇️ const str: string const str = String(bool); console.log(str); // 👉️ "true" console.log(typeof str); // 👉️ "string"
The String function takes a value as a parameter and converts it to a string.
console.log(String(true)); // 👉️ "true" console.log(String(false)); // 👉️ "false"
Alternatively, you can use the toString method to convert a boolean to a string.
const bool = true; console.log(true.toString()); // 👉️ "true" console.log(typeof true.toString()); // 👉️ "string"
The Boolean.toString()
method returns the string representation of the boolean
value.
Another common way to convert a boolean to a string is to interpolate the boolean in a string using a template literal.
const bool = true; console.log(`${bool}`); // 👉️ "true" console.log(typeof `${bool}`); // 👉️ "string"
Template literals are delimited with backticks and allow us to embed variables
and expressions using the dollar sign and curly braces ${expression}
syntax.
The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.
const num = 50; const result = `${num + 50} percent`; console.log(result); // 👉️ 100 percent
Another common way to convert a boolean value to a string is to use the ternary operator.
const bool = true; const str2 = bool ? 'true' : 'false'; console.log(str2); // 👉️ "true" console.log(typeof str2); // 👉️ "string"
The ternary operator is very similar to an if/else
statement.
If the boolean value is true
, then the string true
is returned, otherwise
the string false
is returned.
This is convenient because there are only 2
possible boolean values, so a
shorthand if/else
statement gets the job done.