[Typescript] Sorting arrays in TypeScript

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.

posted @ 2017-03-30 03:06  Zhentiw  阅读(735)  评论(0编辑  收藏  举报