How to use Object.keys() In Typescript

This approach involves using the Object.keys() method to extract all the keys of the object and then checking the length of the resulting array.

Example: In this example, we create an empty object `myObject` and then use the `Object.keys()` method to check if it is empty.

Javascript
const obj1: Record<string, any> = {};
const obj2: Record<string, any> =
  { name: "John", age: 30 };

if (Object.keys(obj1).length === 0) {
  console.log('obj1 is empty'); 
} else {
  console.log('obj1 is not empty');
}

if (Object.keys(obj2).length === 0) {
  console.log('obj2 is empty');
} else {
  console.log('obj2 is not empty'); 
}

Output:

obj1 is empty
obj2 is not empty

How to Check if an Object is Empty in TypeScript ?

In TypeScript, it’s common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null.

Below are the methods to check if an object is empty or not in TypeScript:

Table of Content

  • Using Object.keys()
  • Using Object.entries()
  • Using a for…in loop
  • Using JSON.stringify()

Similar Reads

Using Object.keys()

This approach involves using the Object.keys() method to extract all the keys of the object and then checking the length of the resulting array....

Using Object.entries()

This approach utilizes the Object.entries() method to get an array of key-value pairs from the object and then checks the length of the array....

Using a for…in loop

By iterating through all enumerable properties of the object using a for…in loop, this approach checks if the object has any enumerable properties....

Using JSON.stringify()

Converting the object into a JSON string allows for easy checking if it’s empty by verifying the length of the resulting string....