How to Convert Boolean to String in TypeScript

To convert a boolean to a string in TypeScript, you can use the “String constructor”, “toString()”, “template literals”, or “ternary operator”.

Method 1: Using a String constructor

The String() constructor converts a given argument to a primitive string value.

Example

let boolValue: boolean = true;
let strValue: string = String(boolValue);

console.log(boolValue)
console.log(typeof boolValue)

console.log(strValue)
console.log(typeof strValue)

Output

Convert Boolean to String in TypeScript using String()

Method 2: Using the toString() Method

The toString() method is “used to convert a given object to its string representation.”

Syntax

booleanValue.toString()

Example

let boolValue: boolean = true;
let strValue: string = boolValue.toString();

console.log(boolValue)
console.log(typeof boolValue)

console.log(strValue)
console.log(typeof strValue)

Output

Using the toString() Method

Method 3: Using the template literals

You can use the template literals by wrapping your content inside backticks (` `) instead of single or double quotes. You can use `${expression}` within the template literals to evaluate JavaScript/TypeScript expressions.

Example

let boolValue: boolean = true;
let strValue: string = `${boolValue}`;

console.log(boolValue)
console.log(typeof boolValue)

console.log(strValue)
console.log(typeof strValue)

Output

Using the template literals

Method 4: Using the ternary operator

The ternary operator (conditional operator) is “used to convert a boolean to a string value based on its truthiness.”

Syntax

condition ? valueIfTrue : valueIfFalse

Example

let boolValue: boolean = true;
let strValue: string = boolValue ? 'true' : 'false'

console.log(boolValue)
console.log(typeof boolValue)

console.log(strValue)
console.log(typeof strValue)

Output

Using the ternary operator

This approach is more verbose than the previous ones, but it can be helpful in scenarios where you want to be explicit about the conversion or if you want to provide custom string values for true and false.

That’s it!

Related posts

TypeScript String to Number

TypeScript String to Enum

TypeScript Enum to String

Leave a Comment