How to Check for Both Null and Undefined in TypeScript

Migel Hewage Nimesha Feb 02, 2024
  1. Use Optional Chaining to Check for Both null and undefined in TypeScript
  2. Use Nullish Coalescing to Check for Both null and undefined in TypeScript
  3. Use the == and === Operators to Check for Both null and undefined in TypeScript
How to Check for Both Null and Undefined in TypeScript

TypeScript carries a similar definition for null and undefined. In programming, null refers to some object which is empty or non-existent, and undefined refers to a variable declared without an assigned value.

There are a few different ways that we can use to identify null or undefined, but none of them contains a direct function or a syntax that specifies a null or undefined value directly.

Onwards of TypeScript 3.7, there is a way to identify a null or an undefined value using Nullish Coalescing, Optional Chaining, and the == and === operators.

This article will discuss the methods to check for null and undefined in TypeScript.

Use Optional Chaining to Check for Both null and undefined in TypeScript

Optional chaining (?.) is an operator that we can use to terminate a code from running if it encounters a null or an undefined. Therefore, when it identifies a null or an undefined, it will simply return undefined as the output.

Consider the example below.

const obj =
{
    branch1: {
        emp1: {
            name : "Rory",
            age : 25
        }
    }
}

console.log(obj.branch1.emp1.name)

Output:

Rory

An error message would be returned when no emp1 is mentioned under obj. However, it will return undefined as the output if we use Optional Chaining (?.).

const obj =
{
    branch1: {
    }
}

console.log(obj.branch1?.emp1?.name)

Output:

Undefined

The operator tells not to execute anything if obj.branch.emp1 does not exist and instead returns undefined.

In an instance like,

console.log(obj.branch1?.emp1.name)

It says to access the name element when the emp1 element does not exist; it would return an error message rather than undefined. Therefore, we should manually add the (?.) operator to the elements; otherwise, an error would be returned.

Therefore, undefined can be checked in this method.

Also, Optional Chaining reduces the code and makes it more efficient to access an element rather than using &&. It returns the element, if it exists, with much less code.

Use Nullish Coalescing to Check for Both null and undefined in TypeScript

Nullish Coalescing (??) is another method to identify null and undefined values. When put against null and undefined, it will return to the default value.

There are instances where zero or an empty string are the real values that should be used, but when || is used, it would not return those values. Therefore, using the Nullish Coalescing (??) operator, it is possible to return those values.

Hence || can be replaced with ?? when a default value is used.

Below are a few Nullish Coalescing applications with (??).

null ?? "Value";
// "Value"

undefined ?? "Value";
// "Value"

false ?? true;
// false

0 ?? 100;
// 0

"" ?? "n/a";
// ""

NaN ?? 0;
// NaN

Use the == and === Operators to Check for Both null and undefined in TypeScript

It is possible to use both == and === to perform null and undefined checks in TypeScript.

When the === operator is used to validate a variable with a strict-check method, it will check the type of the variable and the type of the variable’s value and perform a strict undefined check.

Also, we can use == to perform undefined checks in TypeScript. When == is used in the strict-check method, it will only check the type of the value, unlike the === operator.

The == operator can do a null check using the strict-check method. It will return true if a variable is null or even when it is undefined.

It is only possible to perform the strict check for the null using the == operator. In TypeScript, we can check for null and undefined simultaneously by following the juggling-check method.

Example:

var var1: number;
var var2: number = null;

function typecheck(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');
    }
}

typecheck(var1, 'var1');
typecheck(var2, 'var2');

Output:

"var1 == null"

"var1 is undefined"

"var2 == null"

"var2 === null"
Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - TypeScript Undefined