Reputation: 6467
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?
Upvotes: 17
Views: 58462
Reputation: 680
Here is a simple version,
function parseBoolean(value?: string | number | boolean | null) {
value = value?.toString().toLowerCase();
return value === 'true' || value === '1';
}
Upvotes: 0
Reputation: 40534
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
Upvotes: 26
Reputation: 8377
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)
Upvotes: 6
Reputation: 3889
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
Upvotes: 1
Reputation: 6738
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.
Upvotes: 5
Reputation: 16
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;
}
Upvotes: -5