Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Implement NotEmptyCollection definition types #2037

Copy link
Copy link
Open
@jdeniau

Description

@jdeniau
Issue body actions

#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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.