How to Convert String to Boolean in TypeScript [6 Ways]

Here are the five ways to convert a string to a boolean in TypeScript:

  1. Using ternary operator
  2. Using a boolean map
  3. Using JSON.parse()
  4. Using direct comparison with Strict Equality
  5. Using boolean object
  6. Using Double Negation

Method 1: Using the ternary operator

let strValue: string = 'true';
const strToBool = (s: string): boolean => s.toLowerCase() === 'true' ? true : false;
const boolValue = strToBool(strValue)

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

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

Output

Using the ternary operator

Method 2: Using a boolean map

let strValue: string = 'true';

const strToBoolMap: { [key: string]: boolean } = {
  'true': true,
  'false': false
};

const strToBool = (s: string): boolean => strToBoolMap[s.toLowerCase()] || false;
const boolValue = strToBool(strValue)

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

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

Output

Using a boolean map

Method 3: Using JSON.parse() function

let strValue: string = 'true';

const strToBool = (s: string): boolean => {
  try {
    return JSON.parse(s.toLowerCase());
  } catch (error) {
    return false;
  }
};

const boolValue = strToBool(strValue)

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

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

Output

Using JSON.parse() function

Method 4: Using direct comparison with Strict Equality

let strValue: string = 'true';

const strToBool = (s: string): boolean => s.toLowerCase() === 'true';

const boolValue = strToBool(strValue)

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

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

Output

Using direct comparison with Strict Equality

Method 5: Using Boolean object

let strValue: string = 'true';

const strToBool = (s: string): boolean => Boolean(s);

const boolValue = strToBool(strValue)

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

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

Output

Using the Boolean object

Method 6: Using double negation

let strValue: string = 'true';

const strToBool = (s: string): boolean => !!s;

const boolValue = strToBool(strValue)

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

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

Output

Using double negation

The behavior is similar to the direct use of the Boolean object.

Any non-empty string is true, so it will be converted to true.

An empty string is false, so it will be converted to false.

Related posts

TypeScript String to Boolean

TypeScript String to Number

TypeScript String to Enum

TypeScript Enum to String