-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed as not planned
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
array type inference, array filter type inference
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- 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",
),
);
- 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. - What workarounds are you using in the meantime?
The current workaround is either writing custom type guards or type assertions.
hamirmahal
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created