es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

`ObjectLike` should return a not nullable/undefined type

Open dprevost-LMI opened this issue 3 months ago • 5 comments

When running the code below, the IDE indicates that the value can still be undefined/null, although it can't. ObjectLike should potentially use NotNull<T> to assert that the returned value cannot be undefined/null

  const test = undefined;
  if (isObjectLike(test)) {
    test. // error with test can be undefined
  }
Image

Can we use the below for the isObjectLike function definition instead?

export function isObjectLike<T>(value: T): value is NonNullable<T> {
  return typeof value === 'object' && value !== null;
}

dprevost-LMI avatar Aug 30 '25 11:08 dprevost-LMI

I tried to solve this problem myself, but the isObjectLike function in the compat module must behave 100% identically to loadsh, so it must return a boolean, like loadsh's isObjectLike function.

The isObjectLike function documentation incorrectly states that it returns the value is object type and can be used as a type guard, so I created a PR to correct this.

wo-o29 avatar Oct 07 '25 12:10 wo-o29

Hey, thanks for the reply. This is good; it clarifies the compatibility.

In the non-compatibility API, do we have an equivalent? Could we have a similar function, but with proper typing? If so, I could provide in a PR!

dprevost-LMI avatar Oct 09 '25 10:10 dprevost-LMI

As far as I know, there is no function that does the same thing and has type guards, but I think it would be better to wait for the maintainers' answer to find out for sure :)

wo-o29 avatar Oct 09 '25 13:10 wo-o29

As mentioned, the compat version should keep the same types as lodash, so some incorrect parts are intentionally preserved. However, the original function can, of course, be corrected in the right direction.

Could you please explain in what cases this predicate function is needed?

Thank you for filing the issue.

dayongkr avatar Nov 12 '25 02:11 dayongkr

Hey, thanks for the feedback. The use case is to continue with a strongly typed object; considered defined inside the if instead of undefined.

const test = undefined;
//..... test is set to an object
  if (isObjectLike(test)) {
    test. // TSC error with test can be undefined, while if it is an object, it is clearly defined
  }

dprevost-LMI avatar Nov 12 '25 11:11 dprevost-LMI