3 Reasons to use T[ ] over Array<T> in TypeScript
Which Syntax is Better?
TypeScript contains a plethora of tools to shape and define your data.
Today we will discuss 2 options you are given to define arrays:
- Using
T[]
- Using
Array<T>
I believe T[]
is superior, and I will share 3 reasons why this is the case.
So without further ado, let’s dive right in!
1. TypeScript Prefers T[ ]
Lets define two identical arrays using the T[]
and Array<T>
syntax:
Upon hovering over b
, we can see that even the type checker prefers the T[]
syntax over Array<T>
:
Because of this, new developers that adopt the Array<T>
syntax will experience unnecessary confusion.
Seeing types get translated isn’t a friendly developer experience, so it’s beneficial to stick with T[]
syntax, at least when starting out learning TS.
2. Functionality
It turns out the T[]
and Array<T>
are actually functionally identical as of TS Version 5.4.5.
There is however a small nuance in earlier versions of TypeScript:
In previous versions of TypeScript, the example Test2
would actually throw this error:
A rest element cannot follow another rest element.
However, as of TS 5.4.5,both Test1
and Test2
throw errors, which proves they are now truly identical in function.
See this article for more information on this.
Another convenient reason for using T[]
is the fact that most IDEs close square brackets by default.
This means when you type [
, the corresponding ]
bracket is autocompleted for convenience.
This isn’t the case for <
, however there is a way around this.
3. Readability
While readability is considered subjective for both syntaxes, in reality I believe T[]
is superior because it’s easier to type; it’s more convenient.
Take this example, where I define a 3D array using both syntaxes:
Now tell me, does x
read better than y
?
I would argue it’s not even a debate.
Another thing to consider is the way both syntaxes are read in English.
Consider x
: Read it as “A string 3D array”
Consider y
: Read it as “An array of an array of an array of strings”
Again, the T[]
syntax is a clear winner here.
Conclusion
While there is a major divide over which syntax is better, they achieve the same goal functionally.
I believe the T[]
syntax is superior in terms of Readability, and even the TypeScript type checker seems to agree.
Overall, it is up to you which one you choose, but make sure to be consistent to avoid any confusion.
If you enjoyed this article, please make sure to Subscribe, Clap, Comment and Connect with me today! 🌐