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)
bool.TryParsereturnsfalseon "invalid" strings… isn't that the same as returningtrueif string is"true"elsefalse…? Exactly what you're doing already?tryParsein .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.)JSON.parse(string)and if it throws an exception you can infer it is not valid.