'Typescript string to boolean

I am trying to convert a string to boolean. There are several ways of doing it one way is

let input = "true";
let boolVar = (input === 'true');

The problem here is that I have to validate input if it is true or false. Instead of validating first input and then do the conversion is there any more elegant way? In .NET we have bool.TryParse which returns false if the string is not valid. Is there any equivalent in typescript?



Solution 1:[1]

You can do something like this where you can have three states. undefined indicates that the string is not parseable as boolean:

function convertToBoolean(input: string): boolean | undefined {
    try {
        return JSON.parse(input.toLowerCase());
    }
    catch (e) {
        return undefined;
    }
}

console.log(convertToBoolean("true")); // true
console.log(convertToBoolean("false")); // false
console.log(convertToBoolean("True")); // true
console.log(convertToBoolean("False")); // false
console.log(convertToBoolean("invalid")); // undefined

Solution 2:[2]

Returns true for 1, '1', true, 'true' (case-insensitive) . Otherwise false

function primitiveToBoolean(value: string | number | boolean | null | undefined): boolean {
  if (typeof value === 'string') {
    return value.toLowerCase() === 'true' || !!+value;  // here we parse to number first
  }

  return !!value;
}

Here is Unit test:

describe('primitiveToBoolean', () => {
  it('should be true if its 1 / "1" or "true"', () => {
    expect(primitiveToBoolean(1)).toBe(true);
    expect(primitiveToBoolean('1')).toBe(true);
    expect(primitiveToBoolean('true')).toBe(true);
  });
  it('should be false if its 0 / "0" or "false"', () => {
    expect(primitiveToBoolean(0)).toBe(false);
    expect(primitiveToBoolean('0')).toBe(false);
    expect(primitiveToBoolean('false')).toBe(false);
  });
  it('should be false if its null or undefined', () => {
    expect(primitiveToBoolean(null)).toBe(false);
    expect(primitiveToBoolean(undefined)).toBe(false);
  });
  it('should pass through booleans - useful for undefined checks', () => {
    expect(primitiveToBoolean(true)).toBe(true);
    expect(primitiveToBoolean(false)).toBe(false);
  });
    it('should be case insensitive', () => {
    expect(primitiveToBoolean('true')).toBe(true);
    expect(primitiveToBoolean('True')).toBe(true);
    expect(primitiveToBoolean('TRUE')).toBe(true);
  });
});

TypeScript Recipe: Elegant Parse Boolean (ref. to original post)

Solution 3:[3]

You could also use an array of valid values:

const toBoolean = (value: string | number | boolean): boolean => 
    [true, 'true', 'True', 'TRUE', '1', 1].includes(value);

Or you could use a switch statement as does in this answer to a similar SO question.

Solution 4:[4]

If you are sure you have a string as input I suggest the following. It can be the case when retrieving an environment variable for example with process.env in Node

function toBoolean(value?: string): boolean {
  if (!value) {
    //Could also throw an exception up to you
    return false
  }

  switch (value.toLocaleLowerCase()) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

https://codesandbox.io/s/beautiful-shamir-738g5?file=/src/index.ts

Solution 5:[5]

Here is a simple version,

function parseBoolean(value?: string | number | boolean | null) {
    value = value?.toString().toLowerCase();
    return value === 'true' || value === '1';
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 What Would Be Cool
Solution 4 Ronan Quillevere
Solution 5 XzaR