Typescript string to boolean

Viewed 46368

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?

6 Answers

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)

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.

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

Here is a simple version,

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