TypeScript Array Type and Operations

In TypeScript, an array is a special data type used to store a collection of values of the same type. Arrays can contain data of any type, including primitive types (such as numbers, strings, etc.) and object types (such as custom objects, functions, etc.).

The syntax for defining an array is as follows:

let arr: Array<number> = [1, 2, 3, 4, 5];

Here, arr is an array containing five numbers. When defining an array, it is necessary to specify the type of the elements within the array. In the example above, we used Array<number> to declare an array of numbers. If you need to store string-type elements, you can use Array<string>.

In addition to using the Array type, you can also use the shorthand syntax number[] and string[] to define arrays of numbers and strings, respectively. For example:

let numArr: number[] = [1, 2, 3, 4, 5];
let strArr: string[] = ["hello", "world"];

You can access elements in an array using its index. Array indices start from 0, for example:

console.log(arr[0]); // Outputs 1
console.log(strArr[1]); // Outputs "world"

Arrays also support common operations such as adding elements, removing elements, and searching for elements. You can use the push() method to add elements to the end of the array, the pop() method to remove elements from the end of the array, the shift() method to remove elements from the beginning of the array, and the unshift() method to add elements to the beginning of the array. You can use the indexOf() method or the includes() method to find the position of an element in the array. For example:

let fruitArr: string[] = ["apple", "banana", "orange"];
fruitArr.push("pear"); // ["apple", "banana", "orange", "pear"]
fruitArr.pop(); // ["apple", "banana", "orange"]
fruitArr.shift(); // ["banana", "orange"]
fruitArr.unshift("kiwi"); // ["kiwi", "banana", "orange"]
console.log(fruitArr.indexOf("banana")); // Outputs 1
console.log(fruitArr.includes("orange")); // Outputs true