Lists with Arrays and Tuples#

Arrays#

Arrays are used to represent sequential collections of data. In TypeScript, there are two ways of representing arrays:

  1. Using square-bracket notation (i.e. number[]). This is our go-to for simple array types.

  2. Using the generic Array type (i.e. Array<number>). This is our go-to for array types that require more complicated expressions.

As a rule of thumb, we use the Array generic type notation when parentheses would be needed to make the square bracket notation work as expected:

In the code below, we demonstrate array types:

Notice that the type of strsOrNums is (number | string)[], meaning any value in the array may be a number or a string. Even though we know that the first element in strsOrNums is type string and the second element is type number, TypeScript interprets each element as having the same type. If we try to assign an element in the array to a more specific type, we will get an error:

The error is desirable as arrays are intended to be dynamically-sized collections of data whose contents can change over time. For cases where we are certain that an element's type is more specific than the type of the containing array, we have two options:

 

This page is a preview of Beginners Guide to TypeScript

Please select a discussion on the left.