microsoft / microsoft/TypeScript
Suggestion: Array.prototype.sort - remove the need for compareFn to handle undefined values
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
Array.prototype.sort undefined, Array.prototype.sort, sort undefined, extends undefined ? never : T, Array prototype sort, Array.prototype
Suggestion
Based on my understanding of the JS spec the Array.prototype.sort compareFunction is never called on undefined values in an array (they are always sorted to the end of the array).
all undefined elements are sorted to the end of the array, with no call to the compareFunction
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
However, currently the inputs of the compareFn have the type T where T is the types of values in the array. Which forces the developer to make their compare function handle undefined values, despite the compare function never being called with undefined values.
Current
sort(compareFn?: (a: T, b: T) => number
Suggested
sort(compareFn?: (a: T extends undefined ? never : T, b: T extends undefined ? never : T) => number
Use Cases / Examples
The below which is not currently valid would now be valid.
[1, undefined, 2].sort((a: number, b: number) => a - b)
Checklist
My suggestion meets these guidelines:
- 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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the TypeScript declaration for Array.prototype.sort and compare its compareFn parameter with the ECMAScript behavior described in the issue. Check how the proposed conditional type affects arrays containing undefined, callback inference, and existing typings, then validate the suggested example. Done means the intended callback is accepted without changing runtime behavior or introducing unintended compatibility issues.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100