Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New function isEmpty #6

Open
Alexnortung opened this issue Aug 1, 2024 · 2 comments
Open

New function isEmpty #6

Alexnortung opened this issue Aug 1, 2024 · 2 comments

Comments

@Alexnortung
Copy link
Contributor

Let's say I want to get the first item in an array, but i want to make sure that the array is empty first. you can do it in these two ways

if (isNonEmpty(arr)) {
  const first = arr[0];
}

or

if (!isNonEmpty(arr)) {
  return;
}
const first = arr[0];

I would normally prefer the second option as it would allow for less nesting.

The problem is that !isNonEmpty(arr) doesn't really look good and is kinda weird to read (not is not empty). Here it would be much easier to just use isEmpty(arr). This would also read nicely if you want to use !isEmpty(arr) and still feels intuitive.

@uhyo
Copy link
Owner

uhyo commented Aug 1, 2024

You're right that isEmpty is more natural and erogonomic way of expressing this functionality. 😄

However, TypeScript doesn't allow us to do this. Fow now, this must be isNonEmpty in order to perform proper type narrowing.

Playground

function isEmpty<T>(array: readonly T[]): array is readonly [] {
  return array.length === 0;
}

function useArray(array: number[]) {
  if (isEmpty(array)) {
    return;
  }
  const first = array[0];
  //    ^?
  // oops, `first` is still `number | undefined` (with noUncheckedIndexedAccess)
}

function isNonEmpty<T>(array: readonly T[]): array is readonly [T, ...T[]] {
  return array.length !== 0;
}

function useArray2(array: number[]) {
  if (!isNonEmpty(array)) {
    return;
  }
  const first = array[0];
  //    ^?
  // wow, `first` is `number` here
}

@Alexnortung
Copy link
Contributor Author

Ahh I see, that is quite annoying, but it makes sense :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants