Lists with Arrays and Tuples
Arrays#
Arrays are used to represent sequential collections of data. In TypeScript, there are two ways of representing arrays:
Using square-bracket notation (i.e.
number[]
). This is our go-to for simple array types.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:
const numsOrStrs1: (string | number)[] = numbers.concat(strings);
const numsOrStrs2: Array<string | number> = numbers.concat(strings); // preferred
In the code below, we demonstrate array types:
const numbers = [1, 2, 3]; // inferred number[]
const strings = ['a', 'b']; // inferred string[]
const strsOrNums = ['a', 2]; // inferred (number | string)[]
const booleans: boolean[] = [true, false]; // explicit boolean[]
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:
const strsOrNums = ['a', 2];
const myNum: number = strsOrNums[1]; // Error: number | string is not assignable to number
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