How to use JSON.stringify() function In Typescript
In this approach, we are using the JSON.stringify() function in TypeScript to convert the object (obj) into a JSON string. The equality check JSON.stringify(obj) === ‘{}’ checks if the resulting string represents an empty object. If true, it indicates that the original object is empty, printing in the function returning true as output.
Syntax:
JSON.stringify(value, replacer?, space?)
Example: The below example uses JSON.stringify() function to check if an Object is empty in TypeScript.
Javascript
function approach3Fn(obj: Record<string, any>): boolean { return JSON.stringify(obj) === '{}' ; } const obj: Record<string, any> = {}; const res: boolean = approach3Fn(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
Contact Us