Typescript map
Created By: chatGPT
TypeScript provides a powerful way to work with arrays through the use of the
map()
method. This method creates a new array populated with the results of calling a provided function on every element in the original array. This is particularly useful for transforming data. Here’s how you can use it:const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
In the example above, we have an array of numbers. We utilize
map()
to create a new array called doubled
, which contains each number from the original array multiplied by 2. The original array remains unchanged.const originalArray = ['a', 'b', 'c'];
const uppercased = originalArray.map(char => char.toUpperCase());
console.log(uppercased); // Output: ['A', 'B', 'C']
TypeScript also allows you to explicitly type the array elements, providing better code readability and safety. You can specify the type of the elements in the array and the return type of the mapping function.
const numbers: number[] = [1, 2, 3];
const squared: number[] = numbers.map((num: number): number => num * num);
console.log(squared); // Output: [1, 4, 9]
When working with objects, you can also map through an array of objects to transform each object according to your needs. For example, let's say we have an array of user objects, and we want to extract their names:
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const userNames = users.map(user => user.name);
console.log(userNames); // Output: ['Alice', 'Bob']
This example highlights how
map()
can be utilized to extract specific properties from an array of objects. In this case, we obtained an array of names from a more complex structure.const items = [
{ price: 50, quantity: 2 },
{ price: 30, quantity: 3 }
];
const totalPrices = items.map(item => item.price * item.quantity);
console.log(totalPrices); // Output: [100, 90]
The map() method is an essential tool when working with arrays in TypeScript, allowing for efficient data transformation and enhancing code clarity through type safety.
const strings: string[] = ['1', '2', '3'];
const numbersFromString: number[] = strings.map(str => parseInt(str));
console.log(numbersFromString); // Output: [1, 2, 3]