/* Code Comments */

`Type[]` vs `Array<Type>`: What’s the Difference?

June 24, 2019

The short answer: there is no difference.

When investigating, I was steered to the Typescript Handbook¹ 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:


Stephen Weiss

Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!