'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 1:[1]
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)
}
Solution 2:[2]
You can use a validation library for that.
check out class-validator if you want to use classes
or something like Joi if you want to work with plain objects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cursorrux |
| Solution 2 | CY-OD |
