@mirei/ts-collections
    Preparing search index...

    Function singleOrDefault

    • Returns the only element that satisfies the provided type guard predicate, or null when no such element exists.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      • TFiltered

        extends TElement Narrowed element type produced when predicate returns true.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • predicate: TypePredicate<TElement, TFiltered>

        Type guard evaluated for each element. The returned value is narrowed to TFiltered when not null.

      Returns TFiltered | null

      The single matching element, or null when no element satisfies predicate.

      Thrown when more than one element satisfies predicate.

      source is fully enumerated to confirm uniqueness of the matching element.

      const numbers = [5];
      const singleElement = singleOrDefault(numbers);
      console.log(singleElement); // 5

      const numbers2 = [1, 2, 3, 4, 5];
      const singleEven = singleOrDefault(numbers2, x => x > 4);
      console.log(singleEven); // 5

      const empty: number[] = [];
      const singleOfEmpty = singleOrDefault(empty);
      console.log(singleOfEmpty); // null

      const noMatch = [1, 2, 3];
      const singleNoMatch = singleOrDefault(noMatch, x => x > 4);
      console.log(singleNoMatch); // null
    • Returns the only element in the sequence or the only element that satisfies an optional predicate, or null when no such element exists.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • Optionalpredicate: Predicate<TElement>

        Optional predicate evaluated for each element. When provided, the result must be the unique element for which it returns true.

      Returns TElement | null

      The single element or matching element, or null when no element satisfies the conditions.

      Thrown when more than one element exists and predicate is omitted.

      Thrown when predicate is provided and more than one element satisfies it.

      Unlike single, this method communicates the absence of a matching element by returning null.