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.
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:
TypeScript1const myList: number[] = [1, 2, 3, 4]; 2let myString: string = "hello"; 3 4// Now let's try to change the first element of both features 5myList[0] = 100; 6// Attempting to change a string directly will not affect the string 7myString[0] = "t"; // Typescript will flag this as an error 8 9// Instead, we can use the replace method to create a new string 10const newString: string = myString.replace('h', 'H'); 11 12console.log(myList); // prints [100, 2, 3, 4] 13console.log(myString); // prints hello 14console.log(newString); // prints Hello
TypeScript enhances JavaScript's functionality by providing static type checking at compile time, reducing potential runtime errors.
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.
TypeScript1const fruits: string[] = ["apple", "banana", "cherry"]; 2 3// Add a new element at the end 4fruits.push("date"); // ['apple', 'banana', 'cherry', 'date'] 5 6// Inserting an element at a specific position 7fruits.splice(1, 0, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date'] 8 9// Removing a particular element 10fruits.splice(fruits.indexOf("banana"), 1); // ['apple', 'bilberry', 'cherry', 'date'] 11 12// Accessing elements using indexing 13const firstFruit: string = fruits[0]; // apple 14const lastFruit: string = fruits[fruits.length - 1]; // date
TypeScript checks offer additional security, ensuring type adherence when manipulating arrays.
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:
TypeScript1const greetingString: string = "Hello, world!"; 2 3// Accessing characters using indexing 4const firstChar: string = greetingString[0]; // 'H' 5const lastChar: string = greetingString[greetingString.length - 1]; // '!' 6 7// Making the entire string lowercase 8const lowercaseGreeting: string = greetingString.toLowerCase(); // "hello, world!"
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).
TypeScript1const myList: number[] = [1, 2, 3, 4, 5]; 2const myString: string = "Hello"; 3 4// Slicing: `slice` for arrays and `substring` or `slice` for strings 5const sliceList: number[] = myList.slice(2, 4); // [3, 4] 6const sliceString: string = myString.substring(1, 3); // "el" 7 8// Concatenation: `concat` or spread operator for lists and `+` operator or template literals for strings 9const concatenateList: number[] = myList.concat([6, 7, 8]); // [1, 2, 3, 4, 5, 6, 7, 8] 10const concatenateListSpread: number[] = [...myList, 6, 7, 8]; // [1, 2, 3, 4, 5, 6, 7, 8] 11const concatenateString: string = `${myString}, world!`; // "Hello, world!" 12const concatenateStringPlus: string = myString + ", world!"; // "Hello, world!" 13 14// Finding the index of an element in a list or a string 15const indexList: number = myList.indexOf(3); // 2 - Index of element '3' 16const indexString: number = myString.indexOf('e'); // 1 - Index of character 'e' 17 18// Sorting items in array in non-increasing order 19const 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:
TypeScript1const myList: number[] = [1, 2, 3]; 2const 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.
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!