Understanding Arrays and Strings in TypeScript

Introduction

Welcome to this course!

Before diving into TypeScript essentials for interview preparation, let's begin by exploring foundational TypeScript features — specifically, arrays and strings. These features enable TypeScript to group multiple elements, such as numbers or characters, under a single entity, with the added benefit of type safety.

Revising Arrays and Strings

As our starting point, it's crucial to understand how arrays and strings function in TypeScript. An array in TypeScript is a collection with a specified type for its elements, ensuring type safety, which is an enhancement over JavaScript's dynamic typing where errors might only appear at runtime. Arrays are mutable, while strings are immutable. Let's look at some examples:

const myList: number[] = [1, 2, 3, 4];
let myString: string = "hello";

// Now let's try to change the first element of both features
myList[0] = 100;
// Attempting to change a string directly will not affect the string
myString[0] = "t";  // Typescript will flag this as an error

// Instead, we can use the replace method to create a new string
const newString: string = myString.replace('h', 'H');

console.log(myList); // prints [100, 2, 3, 4]
console.log(myString); // prints hello
console.log(newString); // prints Hello

TypeScript enhances JavaScript's functionality by providing static type checking at compile time, reducing potential runtime errors.

Diving Into Lists

Arrays in TypeScript allow us to organize data so that each item holds a definite position or an index. With type safety, TypeScript will warn you if you attempt to assign the wrong type to an element in the array. To modify arrays, the splice method is particularly useful. Splice can add, remove, or replace elements at a specific index. It takes three arguments: the starting index, the number of elements to remove, and optionally, elements to add. This allows for precise manipulation of arrays by modifying their content at specific positions.

const fruits: string[] = ["apple", "banana", "cherry"];

// Add a new element at the end
fruits.push("date"); // ['apple', 'banana', 'cherry', 'date']

// Inserting an element at a specific position
fruits.splice(1, 0, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date']

// Removing a particular element
fruits.splice(fruits.indexOf("banana"), 1); // ['apple', 'bilberry', 'cherry', 'date']

// Accessing elements using indexing
const firstFruit: string = fruits[0]; // apple
const lastFruit: string = fruits[fruits.length - 1]; // date

TypeScript checks offer additional security, ensuring type adherence when manipulating arrays.

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