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.
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()