Skip to content

New rule: no partial array reduce #527

Closed as not planned
Closed as not planned
@danielnixon

Description

Suggestion

A new rule that forbids the partial versions of reduce and reduceRight.

Given:

  const arr: readonly string[] = ...; // may or may not be empty

Would be invalid according to suggested rule:

  // compiles, throws TypeError: Reduce of empty array with no initial value
  const foo = arr.reduce((a, b) => a);

  // compiles, throws TypeError: Reduce of empty array with no initial value
  const bar = arr.reduceRight((a, b) => a);

Would be valid according to suggested rule:

  // compiles, doesn't throw
  const foo = arr.reduce((a, b) => a + b, "");

  // compiles, doesn't throw
  const bar = arr.reduceRight((a, b) => a + b, "");


  // if you can prove to tsc that you have at least one element, the form without `initialValue` is safe:
  const arr: readonly [string, ...(readonly string[])] = [""];
  const foo = arr.reduce((a, b) => a);

This is equivalent to the situation with reduce versus fold in Scala: https://www.wartremover.org/doc/warts.html#iterableops

Metadata

Assignees

No one assigned

    Labels

    Status: Awaiting FeedbackIssue or PR awaits feedback from the community.Type: IdeaMarks an idea, which might be accepted and implemented.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions