Is there a way to check for both `null` and `undefined`?

David Liu picture David Liu · Mar 11, 2015 · Viewed 539.6k times · Source

Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.

Does TypeScript have any dedicated function or syntax sugar for this?

Answer

Fenton picture Fenton · Mar 11, 2015

Using a juggling-check, you can test both null and undefined in one hit:

if (x == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (x === null) {

You can try this with various values using this example:

var a: number;
var b: number = null;

function check(x, name) {
    if (x == null) {
        console.log(name + ' == null');
    }

    if (x === null) {
        console.log(name + ' === null');
    }

    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}

check(a, 'a');
check(b, 'b');

Output

"a == null"

"a is undefined"

"b == null"

"b === null"