TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Prevent mutations

You can add Readonly to prevent unwanted mutations.

const sortArray = (xs: number[]) => xs.sort()
const xs = [3, 1, 2]

console.log(xs) // [3, 1, 2]
console.log(sortArray(xs)) // [1, 2, 3]
console.log(xs) // ⛔️ [1, 2, 3]
const sortArray = (xs: Readonly<number[]>) =>
  xs.sort() // ✅ Does not compile

const sortArray = (xs: Readonly<number[]>) =>
  [...xs].sort()
const xs = [3, 1, 2]

console.log(xs) // [3, 1, 2]
console.log(sortArray(xs)) // [1, 2, 3]
console.log(xs) // ✅ [3, 1, 2]