Skip to content

.tip

· one of the small things

Accept readonly arrays in function parameters

A function that only reads its array argument should say so. readonly T[] accepts both mutable and readonly arrays, and it stops the function from sorting or pushing into something the caller didn't expect to change.

function newest(posts: readonly Post[]): Post | undefined {
  return [...posts].sort(byDate)[0];
}

sort mutates in place. The spread is the fix, and the readonly is what made me spot it.

typescript