Skip to content

Predicate types for partition (and other functions?) #1926

Closed

Description

@joshkel

While investigating switching from Lodash to es-toolkit, I encountered a TypeScript error with code similar to the following:

interface Value {
  name: string;
  good?: boolean;
}
function doSomething(values: Value[]) {
  const [good, bad] = partition(values, i => i.good);
}

Lodash's partition accepts this, because it only requires that its callback returns an unknown. es-toolkit's partition rejects it, because it strictly requires that its callback returns a boolean.

After working with similar tradeoffs in my own projects, I prefer the unknown approach: There are many cases where making a decision based on whether a value is truthy or falsy (not just true or false) is a common and expected idiom, and I've found very few cases where strictly requiring a boolean prevents bugs. (The main one, I suppose, would be catching the scenario of mistakenly using an async function - i.e., accepting a function returning Promise<boolean> when it should be a boolean.) And, perhaps more importantly, accepting unknown is compatible with the TS definitions for JavaScript functions like Array.filter - intuitively, I would expect a utility toolkit's array functions to accept the same predicates as JavaScript's built-in array functions.

Could partition and similar be updated to accept unknown?

(I realize I could use es-toolkit/compat in these cases, but I'm hoping to not rely on compat long term.)

Thank you.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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