Arrays

Arrays are structures that TypeScript inherits from JavaScript. We add type annotations to arrays as usual, but with square brackets at the end to denote that this is an array type.

Let's take a look at an example:

  1. Let's declare the following array of numbers in the TypeScript playground:
const numbers: number[] = [];

Here, we have initialized the array as empty.

  1. We can add an item to the array by using the array's push function. Let's add the number 1 to our array:
numbers.push(1);
We used const to declare the numbers variable and was able to change its array elements later in the program. The array reference hasn't changed – just the elements within it. So, this is fine with the TypeScript compiler.
  1. If we add an element with an incorrect type, the TypeScript compiler will complain, as we would expect:

  1. We can use type inference to save a few keystrokes if we declare an array with some initial values. As an example, if we type in the following declaration and hover over the numbers variable, we'll see the type has been inferred as number[].
const numbers = [1, 3, 5];
  1. We can access an element in an array by using the element number in square brackets. Element numbers start at 0.

Let's take an example:

  1. Let's log out the number of elements under the numbers variable declaration, as follows:
console.log(numbers[0]); 
console.log(numbers[1]);
console.log(numbers[2]);
  1. Let's now click the Run option on the right-hand side of the TypeScript playground to run our program. A new browser tab should open with a blank page. If we press F12 to open the Developer tools and go to the console section, we'll see 1, 3, and 5 output to the console.
  1. There are several ways to iterate through elements in an array. One option is to use a for loop, as follows:
for (let i in numbers) {
console.log(numbers[i]);
}

If we run the program, we'll see 1, 3, and 5 output to the console again.

  1. Arrays also have a useful function for iterating through their elements, called forEach. We can use this function as follows:
numbers.forEach(function (num) {
console.log(num);
});
  1. forEach calls a nested function for each array element, passing in the array element. If we hover over the num variable, we'll see it has been correctly inferred as a number. We could have put a type annotation here, but we have saved ourselves a few keystrokes:

Arrays are one of the most common types we'll use to structure our data. In the preceding examples, we've only used an array with elements having a number type, but any type can be used for elements, including objects, which in turn have their own properties.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172