Skip to content

Implement NotEmptyCollection definition types #2037

Description

@jdeniau

#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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions