Skip to content

Implement NotEmptyCollection definition types #2037

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

Open
jdeniau opened this issue Dec 2, 2024 · 0 comments
Open

Implement NotEmptyCollection definition types #2037

jdeniau opened this issue Dec 2, 2024 · 0 comments

Comments

@jdeniau
Copy link
Member

jdeniau commented Dec 2, 2024

#2001 was a nice addition, but now there is a lot of issue reported like this:

const someList: List<Item>;

if (someList.size === 1) {
  const item: Item = someList.first();
}

This is now reported as an error because .first() might return undefined.

It would be nice to implement NotEmpty collections in that case.

Here is a quick implementation in my codebase:

import { Collection, List, Set } from 'immutable';

export interface NotEmptyCollection<K, V> extends Collection<K, V> {
  first(): V;
  last(): V;
}

export interface NotEmptyList<T> extends List<T> {
  first(): T;
  last(): T;
}

export interface NotEmptySet<T> extends Set<T> {
  first(): T;
  last(): T;
}

export function collectionHasItem<T>(list: List<T>): list is NotEmptyList<T>;

export function collectionHasItem<T>(list: Set<T>): list is NotEmptySet<T>;

export function collectionHasItem<K, T>(
  list: Collection<K, T>
): list is NotEmptyCollection<K, T> {
  return list.count() > 0;
}

export function collectionHasExactlyOneItem<T>(
  list: List<T>
): list is NotEmptyList<T>;

export function collectionHasExactlyOneItem<T>(
  list: Set<T>
): list is NotEmptySet<T>;

export function collectionHasExactlyOneItem<K, T>(
  list: Collection<K, T>
): list is NotEmptyCollection<K, T> {
  return list.count() === 1;
}

It would be great for groupBy function too:

someList
  .groupBy((i) => i.category)
  .map((l: List<Item>) => l.first()) // reported as error, but it can't be
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

1 participant