Exploring Arrays in TypeScript

Lesson Overview

In today's lesson, we'll explore arrays in TypeScript, a versatile and fundamental data structure. An array is an ordered collection of elements that can have specified data types. Just like in other languages, arrays in TypeScript are mutable, meaning their elements can be changed after creation. However, arrays can be made immutable using certain techniques if needed.

The beauty of arrays lies in their simplicity and efficiency; they allow for easy storage, access, and manipulation of data. By the end of this lesson, you'll be able to create, manipulate, and understand the unique applications of arrays in TypeScript.

Understanding Arrays

An array in TypeScript is an ordered collection of elements, which can be of any specified type. This means you can have arrays with elements of the same type or mixed types by specifying a union of allowed types, or you can relax type constraints with the any type if needed.

Consider this TypeScript array declaration as an example:

TypeScript
function createMixedArray(): any[] {
    return ["apple", 42, true, { name: "banana" }, [1, 2, 3]];
}

// Call the function
console.log(createMixedArray());
// Output: ['apple', 42, true, { name: 'banana' }, [1, 2, 3]]

This example demonstrates the syntax for arrays using the any type to allow elements of any type without explicit type annotations. The use of any[] indicates that the function returns an array where each element can be of any type, providing flexibility in mixed-type arrays.

Creating Arrays

Creating Arrays TypeScript allows creating arrays using two main syntaxes: the array literal [] and the Array<type> constructor. Both methods enable you to specify element types, ensuring type safety and predictability.

In the next TypeScript example, we illustrate array creation with specified types:

function createArrays() {
    // Array creation using array literal
    const arrayLiteral: string[] = ["apple", "banana", "cherry"];       
    // Array creation using the Array constructor
    const fromConstructor: Array<string> = new Array("apple", "banana", "cherry");
    return { arrayLiteral, fromConstructor };
}

console.log(createArrays());
// Output: { arrayLiteral: ['apple', 'banana', 'cherry'], fromConstructor: ['apple', 'banana', 'cherry'] }

This example demonstrates the syntax for arrays with a specific type using type annotations.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal