Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get tuple back from filter(Boolean) #182

Open
Flammae opened this issue Jan 29, 2024 · 0 comments
Open

Get tuple back from filter(Boolean) #182

Flammae opened this issue Jan 29, 2024 · 0 comments

Comments

@Flammae
Copy link

Flammae commented Jan 29, 2024

Currently calling the filter(Boolean) method on a tuple turns it into an array of union:

let tuple = ["foo", undefined, "bar", 0] as const;
tuple.filter(Boolean) // ("foo" | "bar")[] 

We can enhance the function to instead return the filtered tuple:

interface ReadonlyArray<T> {
  filter(
    predicate: BooleanConstructor,
    thisArg?: any,
  ): FilterNonFalsy<this>;
}

type FilterNonFalsy<T> = T extends readonly [infer F, ...infer R]
  ? F extends false | 0 | "" | null | undefined | 0n
    ? FilterNonFalsy<R>
    : [F, ...FilterNonFalsy<R>]
  : [];

outputs:

(["1", "2", undefined] as const).filter(Boolean) // now: ["1" | "2"] prev: ("1" | "2")[]

([0, null, undefined, false, ""] as const).filter(Boolean) // now: [] prev: never[]

The order of values in a tuple will most definitely be maintained with this method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant