How to Convert A Value to Boolean in TypeScript


In JavaScript, null, undefined, 0, and "" all evaluate to false in a conditional. What if we want to treat these values as booleans in TypeScript, regardless of the original type?

let w = null;
let x = undefined;
let y = 0;
let z = "";

let boolW: boolean;
let boolX: boolean;
let boolY: boolean;
let boolZ: boolean;

The strict typing prevents us from assigning any of these to a boolean variable.

boolW = w;
boolX = x;
boolY = y;
boolZ = z;
Type 'null' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.
Type 'number' is not assignable to type 'boolean'.
Type 'string' is not assignable to type 'boolean'.

One way to fix this is to use the ternary operator:

boolW = w ? true : false; // false
boolX = x ? true : false; // false
boolY = y ? true : false; // false
boolZ = z ? true : false; // false

But that’s not nice to look at.

What we can do is use this trick:

boolW = !!w; // false
boolX = !!x; // false
boolY = !!y; // false
boolZ = !!z; // false