17

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?

9
  • 3
    I don't know about .NET, but if bool.TryParse returns false on "invalid" strings… isn't that the same as returning true if string is "true" else false…? Exactly what you're doing already? Commented May 17, 2017 at 12:00
  • If someone types "John" John is not a valid bool. That does not mean it is false. Commented May 17, 2017 at 12:04
  • 1
    But isn't that what the .NET thing you described does? I pass it "John", that's not valid, it returns false. I still don't see the difference. Commented May 17, 2017 at 12:06
  • The tryParse in .NET returns both the validness AND the result. (The second parameter is a refference that will be set to the actual outcome, while it returns whether it successfully parsed it or not.) Commented May 17, 2017 at 12:08
  • 2
    You can do JSON.parse(string) and if it throws an exception you can infer it is not valid. Commented May 17, 2017 at 12:40

6 Answers 6

27

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
Sign up to request clarification or add additional context in comments.

3 Comments

I was looking for a builtin function of doing this but it seems that there isn't!
JSON.parse is the closest thing you will come to a built-in way to do this.
It doesn't work if string is in capital. e.g., "False". Therefore, JSON.parse(input) should be JSON.parse(input.toLowerCase())
6

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)

Comments

5

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.

Comments

1

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

Comments

0

Here is a simple version,

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

Comments

-5

I suggest that you want boolVar to be true for input equals true and input equals "true" (same for false) else it should be false.

let input = readSomeInput(); // true,"true",false,"false", {}, ...
let boolVar = makeBoolWhateverItIs(input);

function makeBoolWhateverItIs(input) {
    if (typeof input == "boolean") {
       return input;
    } else if typeof input == "string" {
       return input == "true";  
    }
    return false;
}

5 Comments

Boolean(input) will always return true as long as the string is not empty. So you are basically just doing let boolVar = (input === 'true'), which is the question in the first place. And even if it would work the way you expect, then still it doesn't make a difference between false and a non-boolean string.
Thats not true because Boolean("someOtherString") will return false, Boolean({}) will return false. So if your not sure that your input is a string (let could be any type) this is a good solution. true === "true" will also be false so you have to ensure that the type of input ist String but its let, so it could be everything.
Boolean("someOtherString") will be true. Try it out. From the question I understand that the input will always be a string. And as I said, even if you would be right, than it still doesn't separately check if the parse fails or not.
Also Boolean({}) will return true. And true == 'true' will be false as well.
You are right this does not make any sense to me but your right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.