How to use for…in Loop In Typescript
In this approach, we are using a for…in loop in TypeScript to iterate through the properties of the object (obj). The loop checks if any property is present, and if it is present, it returns false, indicating that the object is not empty. If no properties are found, the function returns true, indicating that the object is empty.
Syntax:
for (const variable in object) {
// code
}
Example: The below example uses for…in Loop to check if an Object is empty in TypeScript.
Javascript
function approach2Fn(obj: Record<string, any>): boolean { for (const key in obj) { if (obj.hasOwnProperty(key)) { return false ; } } return true ; } const obj: Record<string, any> = {}; const res: boolean = approach2Fn(obj); console.log(res); |
Output:
true
Check if an Object is Empty in TypeScript
In TypeScript, checking if an object is empty or not can be done by checking the properties of the object. We can check for the presence of properties in the object using various built-in methods and loops. In this article, we will explore three different approaches for checking if an object is empty or not in TypeScript.
Table of Content
- Using Object.keys() function
- Using for…in Loop
- Using JSON.stringify() function