microsoft / microsoft/TypeScript

Array.prototype.sort make compareFn required in lib.d.ts

Open
#18,286 10 comments 19 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: lib.d.ts Experimentation Needed Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

This is a suggestion to change the signature declaration of Array sort in lib.d.ts from

sort(compareFn?: (a: T, b: T) => number): this;

to

sort(this: string[], compareFn?: (a: string, b: string) => number): this;
sort(compareFn: (a: T, b: T) => number): this;

i.e. make compareFn non-optional for non-string arrays. This would result in errors in cases such as

[2, 10].sort() // returns [10, 2], i.e. sorted lexicographically, which is very unintuitive.

While this is strictly speaking a breaking change, it wouldn't be the first time the typings are stricter than the actually definitions.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the Array.prototype.sort declarations in lib.d.ts and compare them with the proposed overloads. Done means non-string arrays require compareFn while string arrays retain an optional one; check the [2, 10].sort() example against the resulting type behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.