New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array of numbers wrong sort #58160
Comments
This is working as intended. First of all, this is just how JavaScript works, it's completely unrelated to TypeScript. Secondly, the documentation makes clear that the values are converted to strings and then sorted, when no comparer is provided:
Duplicate of #32593. |
@MartinJohns wanted to say that new Float64Array([16, 1, 0, 9, 100]).sort() works correctly |
Yes, different types can behave differently. As documented, when omitting the comparer for
But again, that's just how JavaScript works and completely unrelated to TypeScript. TypeScript won't change how your code is run. |
@MartinJohns |
That's explicitly out of scope for TypeScript. The compiled TypeScript code should behave as-is, just with the types removed. See also: TypeScript Design Goals |
|
Generics only exist at compile time, they're just type information. After compilation anything generic related is completely gone. There's no runtime behavior.
Again, this is explicitly out of scope. See the document I linked. Just provide a comparer if you want numerical sorting for arrays. You might also want this ESlint rule: require-array-sort-compare |
Same for Float64Array or BigInt64Array auto deduction, it's type information. Good rule, but I want to be my code DRY as possible, which could be achieved with Float64Array/BigInt64Array types. |
Those are actual runtime types provided by JavaScript. A
π€·ββοΈ You have to deal with the quirks of the runtime you're dealing with. |
π Search Terms
sort numbers array
π Version & Regression Information
Write array of numbers const numbers: number[] = [16, 1, 0, 9, 100], then sort(),
Result sort will be:
[16, 1, 0, 9, 100]
Expected:
[0, 1, 9, 16, 100]
β― Playground Link
https://www.typescriptlang.org/play?#code/MYewdgzgLgBGCuBbARgUwE4QFxyW9A2gLowC8MBAjAGwA0Ml9ADPQJz2VNNEBQokIADaoAdIJABzABQIUGCCIgh0UKQEo1QA
π» Code
const numbers: number[] = [16, 1, 0, 9, 100]
console.log(numbers.sort())
π Actual behavior
Result sort will be:
[16, 1, 0, 9, 100]
π Expected behavior
Expected:
[0, 1, 9, 16, 100]
Additional information about the issue
Suppose to convert to correct array type in JS
The text was updated successfully, but these errors were encountered: