`type[]` vs `array<type>`: what’s the difference?

2019-06-24

 | 

~1 min read

 | 

164 words

The short answer: there is no difference.

When investigating, I was steered to the Typescript Handbook1 which notes:

The ReadonlyArray type describesArrays that can only be read from. Any variable with a reference to a ReadonlyArray can’t add, remove, or replace any elements of the array.

function foo(arr: ReadonlyArray<string>) {
  arr.slice() // okay
  arr.push("hello!") // error!
}

While it’s good practice to use ReadonlyArrayover Array when no mutation is intended, it’s often been a pain given that arrays have a nicer syntax. Specifically, number[]is a shorthand version of Array<number>, just as Date[] is a shorthand for Array<Date>.

Notice, the final sentence: It’s short hand.

That said, it also introduced to me the concept of the Readonly syntax which is nice and is an opportunity for additional communication to the user about what is expected / constrains the methods implementation from introducing unintended mutation.

Source



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!