Here are the TLDR common methods of defining arrays in TypeScript.
[string]= Tuple (fixed size array)
string= Array (most common array)
Array <string>= Array (same as the 2nd but preferred if you need different types in the array)
When defining an array in TypeScript you might think it is okay to define it using
[string]. I have made this mistake several times & I find others making it often as well. In fact, I still make this mistake. This is actually defining a tuple, which is probably not the array type you are wanting.
The TypeScript handbook does a great job of defining a tuple, which is common in many other languages.
"Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same." - TypeScript Docs on Tuples
let x: [string, number]; x = ["hello", 10];
A common use of tuples is storing output after running a function. This is especially useful for short status messages like writing to a file or submitting an HTTP request.
let status: [string, number] = submitContent(text, urlPath); console.log(status); //(2) ["error", 400]
On a side note, the above example would be a great situation to use destructuring.
let x: string; x = ["hello", "world"]
In cases where the array is mixed with different types I prefer to use the
Array <string> version. It leads to a cleaner syntax in my opinion. It also helps me avoid accidentally getting an error stating "Typescript cannot Invoke an expression whose type lacks a call signature." Here's an example of an array with multiple types.
let x: Array<string | number> x = ["hello", "world", 2]
I often use this when receiving JSON from an API consisting of a list with different types of objects. For example:
let vehicleInventory: Array<Boat | SpaceShip | Wagon>
You might notice that the list of types above are all vehicle types that could possibly share a parent type called
Transportation. Depending on your exact problem, you could solve it with Generics. Another possible solution is to define a type like the following:
type Vehicle = Boat | SpaceShip | Wagon let inventory: Vehicle
In short I use the
string for simple arrays and
Array<string | number> for mixed type arrays. In more rare cases where I have a very small fixed array of known types, I use the tuple version