Borislav Hadzhiev
Fri Mar 11 2022·2 min read
Photo by Cristina Gottardi
To check if an object is empty in TypeScript:
Object.keys()
method to get an array of the object's keys.length
property on the array.length
property is equal to 0
, the object is empty.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.
// 👇️ ['name', 'age'] console.log(Object.keys({ name: 'James', age: 30 }));
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.
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.
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
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.