type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

Add `Truthy` and `Falsy` types

Open bbrk24 opened this issue 3 years ago • 4 comments

The implementation seems pretty straightforward:

type Falsy = Zero | "" | false | null | undefined;
type Truthy<T = Numeric | object | string | symbol | true> = Exclude<T, Falsy>;

Falsy should include NaN, but TypeScript does not provide that at the type level.

Technically, Falsy should also include HTMLAllCollection due to the [[IsHTMLDDA]] internal slot. However, that type is only available for DOM code (not NodeJS) and is deprecated anyways, so I think it's okay to exclude it from this union.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

bbrk24 avatar Apr 30 '22 18:04 bbrk24

Sure. Makes sense.

Although, it should be noted in the docs that Truthy has some restrictions when used as a type-guard: https://github.com/sindresorhus/is/issues/146

A high-quality pull request with proper docs and tests would be welcome: https://github.com/sindresorhus/type-fest/blob/main/.github/contributing.md#submitting-a-new-type

sindresorhus avatar May 02 '22 02:05 sindresorhus

Technically, Falsy should also include HTMLAllCollection due to the [[IsHTMLDDA]] internal slot. However, that type is only available for DOM code (not NodeJS) and is deprecated anyways, so I think it's okay to exclude it from this union.

Yes, should not be included.

sindresorhus avatar May 02 '22 02:05 sindresorhus

Although, it should be noted in the that Truthy has some restrictions when used as a type-guard: sindresorhus/is#146

It seems Exclude doesn't have the same problems Extract does. It does have the problem that you can't Exclude<number, 0> or Exclude<string, ""> -- those get simplified to number and string respectively -- but I think that's a more acceptable limitation.

bbrk24 avatar May 03 '22 14:05 bbrk24

Yup. We just need to make sure to document the limitations.

sindresorhus avatar May 03 '22 14:05 sindresorhus