I want set the return type of this method to check if the value is: null, undefined, '', [], or {}.
/**
* Return true if value is a "empty" val, eg: null, undefined, '', [], {}, 0
*/
export const isNullOrUndefinedOrEmpty = (value: any): value is null | undefined | '' | [] | {} | 0 => {
if (value === null || value === undefined || value === '' || value === 0) {
return true;
}
if (typeof value === 'number' && isNaN(value)) {
return true;
}
if (typeof value === 'object') {
if (Array.isArray(value)) {
return value.length <= 0;
} else {
return Object.keys(value).length === 0 && value.constructor === Object;
}
}
return false;
};
Usage
const testEmpty = {};
if( !isNullOrUndefinedOrEmpty(testEmpty) ){
alert(testEmpty.a)
}
const testNotEmpty = {a: true};
if( !isNullOrUndefinedOrEmpty(testNotEmpty) ){
alert(testNotEmpty.a)
}
But, ts raise this error on both example?
Property 'a' does not exist on type 'never'.
typeof value === 'object'does not check if object has 0 keys (that is{}). UseObject(o).keys.length === 0when o is non empty objecttestNotEmptywhen the negation (!) is removed.