Check if an Object is Empty in TypeScript

avatar

Borislav Hadzhiev

Fri Mar 11 20222 min read

Check if an Object is Empty in TypeScript #

To check if an object is empty in TypeScript:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Access the length property on the array.
  3. If the length property is equal to 0, the object is empty.
index.ts
interface Person { name?: string; age?: number; country?: string; } const person: Person = {}; if (Object.keys(person).length === 0) { console.log('Object is empty'); // 👉️ this runs } else { console.log('Object is NOT empty'); } const isEmpty = Object.keys(person).length === 0; console.log(isEmpty); // 👉️ true

We used the Object.keys method to get an array of all of the keys of the object.

index.ts
// 👇️ ['name', 'age'] console.log(Object.keys({ name: 'James', age: 30 }));
The Object.keys method returns an empty array if the object has no key-value pairs (if it's empty).

If accessing the length property on the array of keys returns anything other than 0, then the object is not empty.

You can create a reusable function if have to perform the check often.

index.ts
interface Person { name?: string; age?: number; country?: string; } const person: Person = {}; function isEmpty(obj: Record<string, any>): boolean { return Object.keys(obj).length === 0; } console.log(isEmpty(person)); // 👉️ true console.log(isEmpty({ name: 'James' })); // 👉️ false

The function takes an object and returns true if the object is empty and false otherwise.

An alternative approach is to try to iterate over the properties of the object. If there is even a single iteration, then the object is not empty.

index.ts
interface Person { name?: string; age?: number; country?: string; } const person: Person = {}; function isEmpty(obj: Record<string, any>): boolean { for (const _key in obj) { return false; } return true; } console.log(isEmpty(person)); // 👉️ true console.log(isEmpty({ name: 'James' })); // 👉️ false
In the code snippet, we have created a helper function which attempts to iterate over the properties of the passed in object.

If there is even 1 iteration, we know that the object has at least 1 key-value pair and is not an empty object.

If there aren't any iterations, then the object is empty.

Use the search field on my Home Page to filter through my more than 1,000 articles.