Mastering Typed Arrays
Typed arrays are arrays where each element is some consistent type.
Annotation and Inference
In most cases, we can rely on type inference for typing arrays.
However, if we initialize an empty array that will receive content later, we need to type annotate explicitly.
Annotating two-dimensional arrays
When you have two-dimensional (or multi-dimensional) arrays, you just append multiple levels to the type.
The first string[]
denotes the inner array. The second []
denotes the outer array.
Why Typed Arrays Matter
TypeScript can infer types when extracting values from a typed array.
Typed arrays prevent incompatible values from being added.
When we use array methods like
map
orreduce
, TypeScript tells us the properties and methods of the current item in the callback because it knows the type.
Multiple Types in Arrays
To support multiple types in arrays, just use the |
operator:
Last updated