let site = ['learnshareit', 2022, true'];
While the statement above is also legal and will be compiled without errors in TypeScript, this practice isn’t recommended.
TypeScript encourages developers to use homogeneous arrays. This means explicitly declaring the data type for the whole array and sticking with it throughout the program. You shouldn’t mix various data types into a single array. Otherwise, you will have a harder time achieving type safety.
But TypeScript allows you to specify which type the array items should hold:
let site: string; site = ['learnshareit', 'quora', 'reddit'];
The first statement is an array declaration, and it requires no initial value. It starts off as undefined and can be given a new value later.
By using type annotation, you can tell TypeScript that site is an array whose items are string values. This is done by naming the type followed by a pair of square brackets.
You can also class generics to define the type of an array. Their syntax looks like this:
let site: Array<string>; site = ['learnshareit', 'quora', 'reddit'];
While they mean basically the same thing, most still prefer the bracket syntax because of its simplicity.
When you don’t include type annotation but give an array some initial values, TypeScript will infer the type from these elements:
let numberArray = ; numberArray = 'a';
Type 'string' is not assignable to type 'number'.
In this example, TypeScript automatically sets the type of the array numberArray to number. Any attempt to assign values of other types to its element will result in errors.
Accessing Array Elements
TypeScript arrays aren’t associative arrays and you have to access their elements through their indexes. In particular, we use nonnegative integers. Arrays are zero-indexed, so the first element is at index 0, the second index, and so on. The last item of an array has the length of the array minus 1 as its index.
Use the square brackets to access elements of an array:
let colors: string = ['orange', 'blue', 'green', 'black']; console.log(colors);
TypeScript doesn’t support negative indexes. Doing so doesn’t lead to errors, but you will receive the undefined value instead of the item you are looking for.
Arrays Of Union Types
TypeScript allows you to create new types from existing ones, such as primitive types (string, number, and boolean).
Using union types, you can combine multiple them together and use them with your arrays. This way, you can still store multiple types in your array in a safe way and take advantage of type checking in TypeScript.
You can form a union type by using the pipe character to separate the member types:
let site: (string | number);
This example creates an array whose item can be either a string or a number. TypeScript understands the union type string | number, accepting all possible values of type string and type number.
After this declaration, you can add values to the array:
site = ['learnshareit', 1, 'TypeScript'];
Remember that the parentheses are important when declaring a union type for arrays. The meaning of the union type would be significantly different without them:
let site: string | number; site = ['learnshareit', 1, 'TypeScript'];
typescript.ts:2:1 - error TS2322: Type '(string | number)' is not assignable to type 'string | number'. Type '(string | number)' is not assignable to type 'number'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
string | number creates a union type of strings and arrays of numbers, not arrays of strings and numbers. When you assign an array whose values aren’t numbers, the compiler detects errors in type compatibility.
Array Of The any Type
When you want your array to accept any type, you can use a special type in TypeScript: any.
This type means you can assign any value, access any property of the value, and do pretty much anything that is syntactically legal.
let anyArray: any = ; anyArray = true; anyArray = 1; anyArray = 'learnshareit'; console.log(anyArray);
[ true, 1, 'learnshareit' ]
Common Array Methods
The push() method
For example, the push() method adds elements to the end of an array and returns the length of the new array:
let colors: string = ['orange', 'blue', 'green', 'black']; console.log(colors.push('white')); console.log(colors);
5 [ 'orange', 'blue', 'green', 'black', 'white' ]
The pop() method
The pop() method removes the last element of an array:
console.log(colors); colors.pop(); console.log(colors);
[ 'orange', 'blue', 'green', 'black', 'white' ] [ 'orange', 'blue', 'green', 'black' ]
The concat() method
To merge two or more arrays, use the concat() method. It doesn’t change any existing array but instead returns the merging result in a new array:
let array1: number = [1, 2, 3]; let array2: number = [4, 5, 6]; let array3 = array1.concat(array2); console.log(array3);
[ 1, 2, 3, 4, 5, 6 ]
The slice() method
TypeScript supports slicing via the slice() method. It returns a portion of an array from start to end positions, which are represented by indexes. Remember that slice() creates a shallow copy and returns it, not modifying the original array in any way.
let colors: string = ['orange', 'blue', 'green', 'black']; console.log(colors.slice(1, 3));
[ 'blue', 'green' ]
The splice() method
If you want to change the contents of an array by modifying it directly, use splice(). It can delete or replace existing elements as well as add new elements to the elements without using a shallow copy.
This example uses splice() to delete one element from index 2 and insert the element ‘red’ in that position:
let colors: string = ['orange', 'blue', 'green', 'black']; colors.splice(1, 1, 'red'); console.log(colors);
[ 'orange', 'red', 'green', 'black' ]
Learn more about TS Array in the article below:
- Convert a Set to an Array in TypeScript
- Check if an Array contains a Value in TypeScript
- Convert an Enum to an Array of Objects in TypeScript
- Declare an Array of Booleans in TypeScript
- Declare an Array of Numbers in TypeScript
- Remove element(s) from an array in typescript
- Declare an Empty Array for a typed Variable in TypeScript
- Declare an Array with Fixed length in TypeScript
- How To Define An Array With Multiple Types In TypeScript
- How to sum a property in an Array of Objects in Typescript
- How to get the sum of an Array of Numbers in Typescript
- Create a Deep Copy of an Array in TypeScript
- How to find an Object in an Array in TypeScript
- Push an object to an Array in TypeScript
- Sort an Array of Strings in Descending order in TypeScript
- Declare a Two-dimensional Array in TypeScript
- Remove Null values from an Array in TypeScript
- Get the Difference between Two Arrays in TypeScript
- Array.find() possibly undefined in TypeScript
- Filter an array of Objects in TypeScript
- Get Enum values as an Array in TypeScript
- Get all Enum Names as an Array in TypeScript
- Find Object in Array by property Value in TypeScript
- How to Empty an Array in TypeScript
- Flatten an Array of Arrays in TypeScript
- Declare a function with an Array return type in TypeScript
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST