Home > Blockchain >  Check if Object is Empty using typescript generic
Check if Object is Empty using typescript generic

Time:10-29

I am new to typescript and in a learning phase. I am trying to create a generic to enforce the following condition

Consider I have a empty object

const data = {}

I need to create a generic which will check the following conditions

Check if its an object if yes, then check if there is any data inside it , else return false

Thanks in advance

CodePudding user response:

const emptyObject = (data:Object) => {
    if(typeof data == "object"){
        if(Object.keys(data).length == 0){
            console.log("Empty Object");
            return true;
        }
        else{
            console.log("Not Empty Object");
        }
    }
    else{
        console.log("Not an Object");
    }
    return false;
} 

Here are some examples and the logs generated.

EXAMPLES

console.log(emptyObject({}));
console.log(emptyObject("acd"));
console.log(emptyObject({
    "acd": 1
}));

LOGS

[LOG]: "Empty Object" 
[LOG]: true 
[LOG]: "Not an Object" 
[LOG]: false 
[LOG]: "Not Empty Object" 
[LOG]: false

CodePudding user response:

const data = {};
console.log("Check if object is empty", Object.keys(data).length == 0);
console.log("Check if it is object", typeof data === "object");
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related