In this lesson we cover all the details of how to sort a list of items using TypeScript. We also present a few tricks to make your sort logic more readable and maintainable using TypeScript.

 

.sort() function is a mutation function, it means it will mutate the original array by default.

To prevent mutation:

const arr: ReadonlyArray<string> = ['foo', 'bar'];
const copy = arr.slice().sort();

Here we use 'ReadonlyArray<T>' to tell Typescript, this is a readonly array of string type. So IDE will tell you if you try to mutate the array.

 

Second, to avoid mutation, we use 'arr.slice()' to copy the original array, then do the sorting.

相关文章:

  • 2022-12-23
  • 2021-10-22
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-15
猜你喜欢
  • 2021-11-07
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2021-12-07
相关资源
相似解决方案