Member-only story
Array declaration syntax in TypeScript: Array<Type>, Type[], and [Type]
In TypeScript, there are three ways to declare an array: Array<Type>
, Type[]
, and [Type]
. These might seem like three interchangeable syntaxes for the same thing, but they actually have different meanings and uses.
Array<Type>
is a generic type that represents an array of a specific type. The syntax is similar to that of a class, with the type being specified between the angle brackets. This is the recommended way to declare an array in TypeScript, as it is the most explicit and type-safe.
For example, the following code declares a variable list
of type Array<string>
, which is an array of strings:
let list: Array<string> = ["item1", "item2", "item3"];
Type[] is a shorthand syntax for Array<Type>. It is equivalent to the example above and can be used interchangeably. The following code declares the same variable list as an array of strings, using the Type[] syntax:
let list: string[] = ["item1", "item2", "item3"];
The third syntax [Type]
is similar to Type[]
in that, it represents an array of a specific type. However, it is actually an alternative way to specify a tuple type.
A tuple is an ordered collection of values, where each value can have a different type. In contrast to an array, a tuple has a fixed length and the types of its elements are known at compile-time. This means that you can access the elements of a tuple using their…