typescriptsorting

How to use toSorted() method in typescript


When I try to use the toSorted method in typescript like this:

const x = [1,2];
const y = x.toSorted();

I got this ts error:

Property 'toSorted' does not exist on type 'number[]'.ts(2339)

this also happen with toReverse() and toSplice() methods


Solution

  • toSorted is a new feature Array.prototype.toSorted() and it exists in ES2023 https://www.sonarsource.com/blog/es2023-new-array-copying-methods-javascript/

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted#browser_compatibility

    This feature are really fresh and it is not supported each browser and code editor. Here you can find an example(JS) https://playcode.io/1521165 or you can use the latest version of TS(today 5.2.0-dev.20230701)

    You can use methods of TypedArray with Array object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

    const x = new Uint8Array([1,2]);
    const y = x.toSorted();
    

    Or you can use a standard sort method

    const numbersArray = [45, 2, 6, 207];
    numbersArray.sort((a: number, b: number) => {
      return a - b;
    });
    

    Demo https://stackblitz.com/edit/typescript-d4dfdn?file=index.ts