Using Array.map() Method in TypeScript

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

Array.map() in TypeScript is the very embodiment of conciseness and efficacy when ye bears the burden to transform thine list of elements without as much as a mutiny against the original array.

Basic Usage

At its core, the map() function calls the provided function once for each element in an array, in order, and constructs a new array from the results.

let numbers = [1, 2, 3, 4];
let doubled = numbers.map((num) => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]

TypeScript and Typing

In TypeScript, type annotations assure that mapping operations can be as sturdy as a two-story outhouse, sticking to the intended types like ants to a picnic spread.

interface Item {
    name: string;
    price: number;
}

let items: Item[] = [
    { name: 'Apple', price: 0.65 },
    { name: 'Orange', price: 0.50 },
];

let prices: number[] = items.map((item) => item.price);

Advanced Mapping

Dive deeper into the map method and you’ll find yourself mapping not just arrays of primitives, but concoctions of interfaces and classes, as intricate as a riverboat’s paddle wheel.

class Product {
    constructor(public name: string, public price: number) {}
    discount(percent: number): number {
        return this.price * (1 - percent / 100);
    }
}

let products: Product[] = [
    new Product('Apple', 0.65),
    new Product('Orange', 0.50),
];

let discounted = products.map(product => ({
    name: product.name,
    price: product.discount(10)
}));

Using map() with Generics

Generics let ye cradle an array of any type as gently as a Mississippi steamboat cradles the night’s gentle sway, whether integers or string melodies, they’re handled with the same tender care.

function mapToArray<T, K>(arr: T[], transform: (val: T) => K): K[] {
    return arr.map(transform);
}

let numbers = [1, 2, 3, 4];
let strings: string[] = mapToArray(numbers, (num) => `Number: ${num}`);

Combining map() with Chainable Methods

Just like a journey down the ol’ Mississippi, combining map with a litany of other methods makes for a smoother voyage. Layer each method akin to how one would layer a high society dame’s petticoat.

let numbers = [1, 2, 3, 4];
let summaries = numbers
    .map(num => ({ value: num, isEven: num % 2 === 0 }))
    .filter(summary => summary.isEven)
    .map(summary => `Number ${summary.value} is even.`);

Conclusion

In closing, skillful use of the map() function in TypeScript is akin to navigating a treacherous river in darkness. Looking back on our journey with map(), from the unvarnished basics to the depths of chainable generics, we see that with a deft hand on the tiller, one can avoid the snags and sandbars, weaving a course through data as sure as a captain steers by the stars.