Search code examples
typescriptundefined

How to check if a field of 'type' is undefined in TypeScript?


I have created a type in TypeScript which is a bit complex (has objects and maps within it).

Is there a way to check if this type has any undefined value or should I go through every part of it to check if it is undefined?

Would typeof be of service in such case?


Solution

  • I have create a recursive function to check an object and its attributes even if it has a nested object and return a boolean

    function checkObjectsForUndefined(myObject:object | undefined):boolean
    { 
    
        if(myObject === undefined)
            return true;
    
        let result = false;
    
        let nestedObjectFlag = false;
    
        let attributes = Object.values(myObject);
    
        for(let i = 0;i<attributes.length;i++)
        {
            if(attributes[i] instanceof Object)
            {
                nestedObjectFlag = true;
    
                result = result || checkObjectsForUndefined(attributes[i])
            }
    
            else
            {
                if(!attributes[i])
                    result = true; 
            }
        }
    
        if(nestedObjectFlag)
            return result;
        else
            return Object.values(myObject).some((value) => !value)
    }