Typescript conversion to boolean
You can use double exclamation sign trick which Typescript does allow and which works fine in JavaScript:
foo(!!xxx);
Alternatively, cast it to any
foo(<any>xxx);
Here is my solution for "typescript": "^3.3.3"
:
function toBool(a: any) {
return Boolean(a).valueOf();
}
export { toBool };
unit test:
import { toBool } from '../../utils/bool';
describe('bool', () => {
describe('#toBool', () => {
it('should convert string to boolean', () => {
expect(toBool('false')).toBeTruthy();
expect(toBool('')).toBeFalsy();
});
it('should convert number to boolean', () => {
expect(toBool(1)).toBeTruthy();
expect(toBool(0)).toBeFalsy();
expect(toBool(-1)).toBeTruthy();
expect(toBool(Infinity)).toBeTruthy();
expect(toBool(-Infinity)).toBeTruthy();
});
it('should convert null to boolean', () => {
expect(toBool(null)).toBeFalsy();
});
it('should convert undefined to boolean', () => {
expect(toBool(undefined)).toBeFalsy();
});
it('should convert NaN to boolean', () => {
expect(toBool(NaN)).toBeFalsy();
});
it('should convert object to boolean', () => {
expect(toBool({})).toBeTruthy();
});
it('should convert array to boolean', () => {
expect(toBool([])).toBeTruthy();
});
});
});
unit test results:
PASS src/__tests__/utils/bool.spec.ts
bool
#toBool
✓ should convert string to boolean (3ms)
✓ should convert number to boolean (1ms)
✓ should convert null to boolean (1ms)
✓ should convert undefined to boolean
✓ should convert NaN to boolean (1ms)
✓ should convert object to boolean (1ms)
✓ should convert array to boolean
Test Suites: 1 passed, 1 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 3.79s, estimated 4s
While you can't cast a number directly to a boolean, you can cast it to the wrapper Boolean class and immediately unwrap it. For example:
foo(<boolean><Boolean>xxx);
While clumsy, it avoids the type erasure of casting to <any>
. It's also arguably less obscure & more readable than the !!
approach (certainly so in the transpiled js code).
With TypeScript 2.0.2 you can do this:
type Falsey = '' | 0 | false | null | undefined;
function eatFruit(fruit: string | Falsey) {
if (fruit) {
alert(`Ate ${fruit}`);
} else {
alert('No fruit to eat!');
}
}
const fruits = ['apple', 'banana', 'pear'];
eatFruit(fruits[0]); // alerts 'Ate apple'
eatFruit(fruits[1]); // alerts 'Ate banana'
eatFruit(fruits[2]); // alerts 'Ate pear'
eatFruit(fruits[3]); // alerts 'No fruit to eat!'
const bestBeforeDay = 12;
let day = 11;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'Ate peach'
day += 1;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'No fruit to eat!'
let numMangos = 1;
eatFruit(numMangos && 'mango'); // alerts 'Ate Mango'
numMangos -= 1;
eatFruit(numMangos && 'mango'); // alerts 'No fruit to eat!'