What is an Array?
An array is a data structure that stores multiple values in a single variable.
Important characteristics:
- An array stores multiple elements.
- Elements are accessed using indexes.
- JavaScript arrays are dynamic in size.
- TypeScript can enforce the type of each element.
- Arrays are zero-indexed.
- Arrays are objects in JavaScript.
Creating Arrays in TypeScript
1. Array Literal Syntax []
This is the most common and recommended way to create an array.
You can also create an empty array:
The important difference is when you pass a single number:
Array Type Annotation in TypeScript
Basic Syntax
Object array
Union Types in Array Annotation
What if you want an array that accepts both numbers and strings?
Use a union type.
Multidimensional Array Annotation
An array can contain other arrays.
For example, a matrix:
7. Readonly Array Annotation
If you don't want an array to be modified, use readonly.
Type Inference with as const
Now let's understand something different.
The inferred type becomes:
Type Inference with Empty Arrays
This is one of the most important situations.
Consider:
What type does TypeScript infer?
It depends on the TypeScript configuration and context. In common strict configurations, this may be inferred as never[] initially.
What is never[]?
It is an array whose element type is never, meaning no value can be assigned as an element.
For example:
Therefore, when creating an empty array, explicitly specify the intended type:
This avoids inference problems.