Skip to content

Improve type inference in array filtering.Β #62376

@pjdotson

Description

@pjdotson

πŸ” Search Terms

array type inference, array filter type inference

βœ… Viability Checklist

⭐ Suggestion

Currently, the type inference when calling Array.filter could be improved. Look at this code snippet:

const arr1: [number, undefined] = [1, undefined];
const filtered1 = arr1.filter((v) => v != null);
// type of filtered1 is number[]

const arr2: [number, undefined] = [1, undefined];
const filtered2 = arr2.filter((v) => v != null && v != 0);
// type of filtered2 is (number | undefined)[]

It seems like the type of filtered2 should be number[], since filtered2 is a subset of filtered1. However, the type inference, with the more specific filter does not narrow the type as much as it could.

πŸ“ƒ Motivating Example

This feature is a minor improvement that could remove some existing type guards and type assertions while still emitting correctly typed code.

πŸ’» Use Cases

  1. What do you want to use this for? To get rid of some of the type inferences in our code base, like this:
      const keys = unique.unique(
        lines
          .flatMap((l) => [l.channels.y, l.channels.x])
          .filter(
            (v): v is channel.Key => v != null && v != 0 && typeof v === "number",
          ),
      );
  1. What shortcomings exist with current approaches?
    The short coming is that we need to write more verbose code & do things that typically feel like weakening type safety (like type assertions) for types that should be easily inferred by the TypeScript compiler.
  2. What workarounds are you using in the meantime?
    The current workaround is either writing custom type guards or type assertions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions