Check if a String is Null or Empty in TypeScript

As a developer, you often need to check if a string is null or empty in TypeScript. In this tutorial, I will explain how to check if a string is null or empty in TypeScript. When working with strings in TypeScript, it’s common to determine whether a string is null, undefined, or an empty string. Let’s explore different approaches to handle these cases with examples.

Why Check for Null or Empty Strings in TypeScript?

Let’s say you’re building a form for a U.S.-based e-commerce site. You ask users to enter their first name and last name, and you get responses like:

const firstName = "John";
const lastName = "";

Or sometimes:

const firstName = null;
const lastName = undefined;

If you try to use these values without checking them, your app may crash or behave unpredictably. That’s why null and empty checks are essential.

Understanding Null, Undefined, and Empty Strings in TypeScript

Let’s clarify the difference between the three main values you might want to check for:

ValueMeaning
nullA null value represents a deliberate non-value or absence of any object value. It is an explicit assignment indicating that the variable does not refer to any object.
undefinedUndefined means a variable has been declared but has not been assigned a value. It is the default value for uninitialized variables. Overall, the variable is declared but not assigned.
"" (empty)An empty string is a string with zero characters. It is represented by a pair of quotation marks with nothing in between ("").

In TypeScript, we often want to check for all three when validating string inputs.

Check out Remove Empty Strings from an Array in TypeScript

Check if a String is Null or Empty in TypeScript

Now, let me show you different methods to check if a string is null or empty in TypeScript.

Method 1: Using Simple if Conditions

This is the most basic and beginner-friendly method to check for null or empty strings in TypeScript. It uses traditional if statements to evaluate different possibilities one by one. This method is very readable and easy to debug.

function isNullOrEmpty(input: string | null | undefined): boolean {
  if (input === null || input === undefined || input.trim() === "") {
    return true;
  }
  return false;
}

const name = "";
console.log(isNullOrEmpty(name)); // true

const nickname = "Emily";
console.log(isNullOrEmpty(nickname)); // false

Here is how it works:

  • input === null: Checks if value is null.
  • input === undefined: Checks if variable is declared but not initialized.
  • input.trim() === "": Checks if the string is empty or only contains whitespace.

I executed the above TypeScript code, and you can see the exact output in the screenshot below:

Check if a String is Null or Empty in TypeScript

To check if a string is null or undefined in TypeScript, you can use the strict equality operator (===) or the typeof operator. Here’s an example:

function isNullOrUndefined(str: string | null | undefined): boolean {
  return str === null || str === undefined;
}

const name1: string | null = "John";
console.log(isNullOrUndefined(name1)); // Output: false

const name2: string | null = null;
console.log(isNullOrUndefined(name2)); // Output: true

const name3: string | undefined = undefined;
console.log(isNullOrUndefined(name3)); // Output: true

In this example, we define a function isNullOrUndefined that takes a string parameter that can be null or undefined. The function uses the strict equality operator to compare the string with null and undefined. If either condition is true, the function returns true, indicating that the string is null or undefined.

Check out Create and Use an Empty String Array in TypeScript

Method 2: Using Optional Chaining with trim()

Optional chaining (?.) is a modern TypeScript feature that lets you safely access properties or methods, even if the variable might be null or undefined. It simplifies null checks and avoids long conditional statements.

Here is how you can use it:

function isNullOrEmpty(input?: string | null): boolean {
  return input?.trim() === "" || input == null;
}

const email = null;
console.log(isNullOrEmpty(email)); // true

const username = "brian77";
console.log(isNullOrEmpty(username)); // false

Here is how it works:

  • input?.trim() runs .trim() only if input is not null or undefined.
  • input == null is a loose equality check that returns true for both null and undefined.

You can see the output in the screenshot below:

TypeScript Check if a String is Null or Empty

Read Convert Date to String Format DD/MM/YYYY in TypeScript

Method 3: Create a Utility Function with Type Guards

Type guards help you write safe, reusable logic in a way TypeScript understands at compile time. This method is perfect for applications where you may receive inputs of unknown types (e.g., from an API or dynamic form).

Here is the complete code:

function isStringNullOrEmpty(input: unknown): input is string {
return typeof input !== "string" || input.trim() === "";
}

const zipCode = " ";
if (isStringNullOrEmpty(zipCode)) {
  console.log("Invalid ZIP code.");
} else {
  console.log("ZIP code accepted.");
}

Here is how it works:

  • typeof input !== "string" filters out non-string values like numbers or booleans.
  • input.trim() === "" checks for empty strings.

Method 4: Using Lodash Utility Functions

Lodash is a popular JavaScript utility library. If you’re already using Lodash in your TypeScript project, you can leverage its built-in functions to make null and empty checks even simpler.

If you have not installed Lodash, then you can use this cmdlet to install it.

npm install lodash

Here is the full TypeScript code.

import { isNil, isEmpty } from "lodash";

function isNullOrEmptyLodash(input: any): boolean {
  return isNil(input) || isEmpty(input.trim?.());
}

const state = undefined;
console.log(isNullOrEmptyLodash(state)); // true

const city = "Houston";
console.log(isNullOrEmptyLodash(city)); // false

Here is how it works:

  • isNil(input) returns true if input is null or undefined.
  • isEmpty() checks for an empty value (empty string, array, etc).
  • input.trim?.() safely calls trim if it’s available.

Read Check if a String is a Number in TypeScript

Method 5: Using Regular Expressions (Regex)

Regex is a powerful pattern-matching tool. While not always necessary for simple checks, it’s handy when you want to validate strings containing only whitespace or special patterns.

Here is the complete code:

function isNullOrEmptyRegex(input: string | null | undefined): boolean {
  return !input || !/\S/.test(input);
}

const feedback = "    ";
console.log(isNullOrEmptyRegex(feedback)); // true

const comment = "Great app!";
console.log(isNullOrEmptyRegex(comment)); // false

This is how the code works:

  • \S is a regex pattern that matches any non-whitespace character.
  • !/\S/.test(input) returns true if the input is all whitespace or empty.

Here is the exact output in the screenshot below:

How to Check if a String is Null or Empty in TypeScript

Check out Convert Date to String in TypeScript

Real Example: Validate a Signup Form

Let’s consider a real-world scenario where you have a user registration form in a web application. One of the fields is for the user’s email address, which is a required field. You want to ensure that the user enters a valid email address before submitting the form.

Here’s an example of how you can handle the email field validation in TypeScript:

function validateEmail(email: string | null | undefined): boolean {
  if (email === null || email === undefined || email.trim() === "") {
    console.log("Please enter a valid email address.");
    return false;
  }

  // Additional email format validation logic...

  return true;
}

const userEmail1 = null;
console.log(validateEmail(userEmail1)); // Output: Please enter a valid email address. false

const userEmail2 = "";
console.log(validateEmail(userEmail2)); // Output: Please enter a valid email address. false

const userEmail3 = "  ";
console.log(validateEmail(userEmail3)); // Output: Please enter a valid email address. false

const userEmail4 = "john@example.com";
console.log(validateEmail(userEmail4)); // Output: true

In this example, we define a validateEmail function that takes an email parameter that can be null, undefined, or a string. The function first checks if the email is null, undefined, or an empty string (after trimming). If any of these conditions are true, it logs an error message and returns false, indicating an invalid email.

If the email passes the null, undefined, and empty string checks, you can perform additional email format validation logic to ensure the email is in a valid format (not shown in the example).

We demonstrate the usage of the validateEmail function with different email values. userEmail1 is null, userEmail2 is an empty string, and userEmail3 contains only whitespace characters. All three cases fail the validation, and the function logs the error message and returns false. userEmail4 contains a valid email address, so the function returns true.

Conclusion

In this tutorial, we explored different approaches to check if a string is null or empty in TypeScript. We learned how to handle null and undefined values using strict equality comparison and how to check for an empty string by comparing it with an empty string literal.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.