Convert a Boolean to a String in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 19, 2022

banner

Photo from Unsplash

Convert a Boolean to a String in TypeScript #

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.

index.ts
// 👇️ 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.

index.ts
console.log(String(true)); // 👉️ "true" console.log(String(false)); // 👉️ "false"

Alternatively, you can use the toString method to convert a boolean to a string.

index.ts
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.

index.ts
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.

index.js
const num = 50; const result = `${num + 50} percent`; console.log(result); // 👉️ 100 percent
By interpolating the boolean value as a variable in the template literal, it gets converted to a string.

Another common way to convert a boolean value to a string is to use the ternary operator.

index.ts
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 expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right of the colon is returned.

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.

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.