Skip to content

Warn when Array.sort is used without a callback on non-string arrays #35551

Description

@iansan5653

Search Terms

array.sort, sort, numeric array sort, alphabetic array sort

Suggestion

Give a warning when Array.sort is called without a callback on an array that is not of type string[].

Use Cases

By default Array.sort() sorts the array by the elements' UTF-16 code-point values after converting the array values to strings. This means that you'll get unexpected hidden results if you call sort on a numeric array (or any non-string array really). If you're intimately familiar with JavaScript, this is understood, but if you're coming from another language this would be surprising, unexpected, and hard to find.

Examples

// Don't warn - this will give the expected result
["a", "d", "b", "f", "bat"].sort() // -> ["a", "b", "bat", "d", "f"]

// Warn - this is almost definitely a mistake
[0, 1, 2, 3, 20, 10].sort() // -> [0, 1, 10, 2, 20, 3]

// Warn - this is most likely not the expected result
[1, true, false, 0].sort() // -> [0, 1, false, true]

// Don't warn - a callback was provided to handle numbers
[0, 1, 2, 3, 20, 10].sort((a, b) => a - b) // -> [0, 1, 2, 3, 10, 20]

Another example is microsoft/vscode#86440, where this mistake found its way into production code.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • Not sure about this.
  • 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions