Typescript 101 – the some() method

Typescript 101 - the some() method

This is the sixth post of a blog series where each post will touch a popular TypeScript method, function or feature with example. If you’re starting with TypeScript (or JavaScript) you might not be familiar with all of these powerful tools that can shorten your codebase and help you in day to day development

This post we will discuss the .some() method.

.some()

Let’s say an API call like:

const result = await service.retrieveDrinkers.promise();

Returns a list of beer loving engineers which looks like this:

const drinkers = [
    {
        name: 'marcel',
        beers: 5,
        paid: false
    },
    {
        username: 'roger',
        beers: 8,
        paid: true
    },
    {
        username: 'jan',
        beers: 6,
        paid: true
    },
    {
        username: 'dirk',
        beers: 4,
        paid: true
    }
];

Let’s say we would like to quickly check if there is any engineer amongst the happy drinkers that did not pay their part of the bill yet. Well we can because the following line of code:

const someoneDidNotPay = drinkers.some(person => !person.paid);

results in true since as always Marcel is the slacker of the group.

Summary

So how does it work ? The .some() method gets passed a function that runs for each value in the array. It will then check if the value matches the condition. The function will return a boolean. Keep in mind that as soon as one true is returned from the function, then .some()  itself will return true. Which sounds confusing but if you look at the example above it means the result is already true on the first hit which is Marcel and therefor .some() will stop processing further.

Make sure to also check our other TypeScript 101 posts.

Hope it helps!