Languages
[Edit]
EN

TypeScript - convert string to boolean

0 points
Created by:
Niac
508

In TypeScript it is possible to parse string to boolean in following ways.

1. Equality operator example

const text: string = 'true';
const value: boolean = text == 'true';

console.log(value); // true

2. JSON parse operation example

function parseBoolean(text: string): boolean {
  const value = JSON.parse(text);

  if (typeof value != 'boolean') throw new Error('Incorrect type!');

  return value;
}

const text: string = 'true';
const value: boolean = parseBoolean(text);

console.log(value); // true

3. Regular expression example

const truthExpression = /^(TRUE|True|true|YES|Yes|yes|ON|On|on|1|T|t|Y|y)$/g;
const falsyExpression = /^(FALSE|False|false|NO|No|no|OFF|Off|off|0|F|f|N|n)$/g;

function parseBoolean(text: string): boolean {
  if (truthExpression.test(text)) return true;

  if (falsyExpression.test(text)) return false;

  throw new Error('Incorrect value!');
}

const text: string = 'true';
const value: boolean = parseBoolean(text);

console.log(value); // true

4. Custom function example

function parseBoolean(value: string | number | boolean): boolean {
  switch (value) {
    case 1:
    case true:
    case '1':
    case 'true':
    case 'True':
    case 'TRUE':
    case 'on':
    case 'On':
    case 'ON':
    case 'yes':
    case 'Yes':
    case 'YES':
    case 't':
    case 'T':
    case 'y':
    case 'Y':
      return true;

    case 0:
    case false:
    case '0':
    case 'false':
    case 'False':
    case 'FALSE':
    case 'off':
    case 'Off':
    case 'OFF':
    case 'no':
    case 'No':
    case 'NO':
    case 'f':
    case 'F':
    case 'n':
    case 'N':
      return false;

    default:
      throw new Error('Incorrect value!');
  }
}

const text: string = 'true';
const value: boolean = parseBoolean(text);

console.log(value); // true
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join