How to Check if an Object is Empty in TypeScript

In TypeScript, to check if an object is empty (i.e., it has no enumerable properties), you can use the “Object.keys()” function and check the length of the returned array.

Method 1: Using the Object.keys() method

Here are the steps to check if an Object is Empty in TypeScript:

  1. Using the Object.keys() Method
  2. Access the length property on the array.
  3. If the length property is equal to 0, the object is empty.

Example

function isEmpty(obj: object): boolean {
  return Object.keys(obj).length === 0;
}

const obj1 = {};
const obj2 = { key: "value" };

console.log(isEmpty(obj1));
console.log(isEmpty(obj2));

Output

Check if an Object is Empty in TypeScript using Object.keys()

Method 2: Using a for…in loop in TypeScript

To check if an object is empty using a for…in loop in TypeScript, you can iterate over the object’s properties. If you encounter any property during the iteration, you can determine that the object is not empty. If the loop completes without finding any properties, then the object is empty.

Example

function isEmpty(obj: object): boolean {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}

// Test cases:
const obj1 = {};
console.log(isEmpty(obj1));

const obj2 = { name: "John" };
console.log(isEmpty(obj2));

Output

Using a for...in loop in TypeScript

Method 3: Using lodash in TypeScript

To check if an object is empty using lodash in TypeScript, you can use the “isEmpty()” method provided by lodash. This method works for arrays, strings, maps, sets, and objects.

Example

First, you’ll need to install lodash if you haven’t already:

npm install lodash

Then, you can use the isEmpty() method in your TypeScript code:

const _ = require('lodash');

function isObjectEmpty(obj: object): boolean {
  return _.isEmpty(obj);
}


const obj2 = { name: "John" };
console.log(isObjectEmpty(obj2));

Output

false

The lodash isEmpty() function provides a very convenient way to check for emptiness across various data structures, so it’s often a good choice if you’re already using lodash in your project.

That’s it!

Related posts

How to Check If an Object is an Array in TypeScript

Leave a Comment