ar099968
ar099968

Reputation: 7547

Typescript: method to check if value is: null, undefined, '', [], or {}

Typescript Playground

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'.

Upvotes: 1

Views: 867

Answers (1)

Bbrk24
Bbrk24

Reputation: 919

The type {} in TypeScript does not mean "empty object", it means "any value besides null or undefined".

The library type-fest provides an EmptyObject type:

declare const emptyObjectSymbol: unique symbol;
type EmptyObject = {[emptyObjectSymbol]?: never};

source: https://github.com/sindresorhus/type-fest/blob/main/source/empty-object.d.ts

Upvotes: 2

Related Questions