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.

Understanding Strings

Think of strings as a sequence of letters or characters in TypeScript. Strings are enclosed by double quotes or single quotes and benefit from TypeScript's type inference:

const greetingString: string = "Hello, world!";

// Accessing characters using indexing
const firstChar: string = greetingString[0]; // 'H'
const lastChar: string = greetingString[greetingString.length - 1]; // '!'

// Making the entire string lowercase
const lowercaseGreeting: string = greetingString.toLowerCase(); // "hello, world!"
Indexing and Common Operations

Both arrays and strings in TypeScript allow us to access individual elements through indexing, enhanced by the static typing system. Let's explore common operations:

  • Slicing: The slice method is used for both arrays and strings. For arrays, slice creates a shallow copy of a portion of the array. The method takes two arguments: the starting index and the optional end index (exclusive).
const myList: number[] = [1, 2, 3, 4, 5];
const myString: string = "Hello";

// Slicing: `slice` for arrays and `substring` or `slice` for strings
const sliceList: number[] = myList.slice(2, 4); // [3, 4]
const sliceString: string = myString.substring(1, 3); // "el"

// Concatenation: `concat` or spread operator for lists and `+` operator or template literals for strings
const concatenateList: number[] = myList.concat([6, 7, 8]); // [1, 2, 3, 4, 5, 6, 7, 8]
const concatenateListSpread: number[] = [...myList, 6, 7, 8]; // [1, 2, 3, 4, 5, 6, 7, 8]
const concatenateString: string = `${myString}, world!`; // "Hello, world!"
const concatenateStringPlus: string = myString + ", world!"; // "Hello, world!"

// Finding the index of an element in a list or a string
const indexList: number = myList.indexOf(3); // 2 - Index of element '3'
const indexString: number = myString.indexOf('e'); // 1 - Index of character 'e'

// Sorting items in array in non-increasing order
const sortedList: number[] = [...myList].sort((a, b) => b - a); // [5, 4, 3, 2, 1]

The spread operator (...) creates a shallow copy of the array. When concatenating arrays, this means that changes to nested objects in one array will reflect in the concatenated array. For example:

const myList: number[] = [1, 2, 3];
const extendedList = [...myList, 4, 5]; // Creates a new array with added elements [1, 2, 3, 4, 5]

However, if myList contained objects, modifications to those objects would appear in both myList and extendedList because only references to the objects are copied, not the objects themselves.

When sorting with the sort((a, b) => b - a) method, TypeScript sorts arrays by comparing pairs of elements. The sort method uses the comparison function (a, b) => b - a to determine the order. If b - a returns a positive value, the order of b and a is swapped to sort the array in non-increasing order.

TypeScript's type system offers additional assurances, such as preventing unintended assignments and enhancing understanding of operations.

Summary

Congratulations on navigating through arrays and strings in TypeScript! You've learned how to create, access, and manipulate them using various operations with the added security of strong typing.

Up next, reinforce your understanding with hands-on practice. Leverage TypeScript’s type safety to improve your coding efficiency and reduce errors, preparing you to tackle more complex programming challenges. Happy coding!

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