In TypeScript, an array is a data structure that stores a collection of elements, which can be of any type, though typically of the same type. Arrays allow you to store multiple values in a single variable and access them via their index.
Creating Arrays in TypeScript
1. Array of a specific type:
You can define an array to contain elements of a specific type using the following syntax:
let numbers: number[] = [1, 2, 3, 4];
let strings: string[] = ["Apple", "Banana", "Orange"];
2. Using the Array generic type:
Another way to define an array is by using the Array<T> syntax, where T is the type of elements in the array:
let numbers: Array = [1, 2, 3, 4];
let strings: Array = ["Apple", "Banana", "Orange"];
Multi-dimensional Arrays
You can also create multi-dimensional arrays (arrays of arrays) in TypeScript:
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Array Methods
TypeScript arrays inherit many useful methods from JavaScript, such as:
push() – Adds elements to the end of the array.
pop() – Removes and returns the last element.
shift() – Removes and returns the first element.
unshift() – Adds elements to the beginning of the array.
map() – Creates a new array by applying a function to each element.
filter() – Creates a new array with all elements that pass a test.
reduce() – Reduces the array to a single value by applying a function.
Example:
let fruits: string[] = ["Apple", "Banana", "Orange"];
fruits.push("Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Mango"]
What is Array in Typescript – Interview Questions
Q 1: What is an array in TypeScript?
Q 2: How to declare an array in TypeScript?
Q 3: Can arrays store mixed types?
Q 4: Are array methods same as JavaScript?
Q 5: Is array type checking available?
What is Array in Typescript – Objective Questions (MCQs)
Q1. Which symbol is used to define a TypeScript array type (method 1)?
Q2. How do you declare a number array?
Q3. Which method adds an element at the end of an array?
Q4. Array type can also be declared using:
Q5. What is the index of the first element of an array?