1

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

2
  • typeof value === 'object' does not check if object has 0 keys (that is {}). Use Object(o).keys.length === 0 when o is non empty object Commented Oct 19, 2022 at 12:48
  • Interestingly, the compilation error disappears in the second example with testNotEmpty when the negation (!) is removed. Commented Oct 19, 2022 at 12:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively Record<never, never>
Quote from the documentation on EmptyObject: " Unfortunately, Record<string, never>, Record<keyof any, never> and Record<never, never> do not work. See {@link github.com/sindresorhus/type-fest/issues/395 #395}."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.