Explain Codes LogoExplain Codes Logo

How do I check whether an array contains a string in TypeScript?

javascript
array-methods
typescript
javascript-features
Nikita BarsukovbyNikita Barsukov·Oct 16, 2024
TLDR

Utilize includes() to check if a string is present in an array:

const pokemon = ['Bulbasaur', 'Pikachu', 'Charizard']; const foundPikachu = pokemon.includes('Pikachu'); // Pikachu, I choose you!

The includes() function scans the array and returns true if the given string is an array member, otherwise false.

Graduating from Pallet Town

You've harnessed the power of includes(), but, like Ash Ketchum, you may find that you require additional array mastery on your journey:

  • indexOf() can locate the position of our string within the array, returning -1 if it takes a holiday:
const pokemon = ['Bulbasaur', 'Pikachu', 'Charizard']; const positionedPikachu = pokemon.indexOf('Pikachu'); // returns 1, because arrays start at 0. const pikachuExists = positionedPikachu !== -1; // Pikachu is not MIA (Missing in Array)
  • For arrays of objects, use find() or some() to check for a string within an array's properties:
const pastas = [{name: 'spaghetti'}, {name: 'tortellini'}]; const hasTortellini = pastas.some(pasta => pasta.name.includes('tortellini')); // Don't pasta up this opportunity
  • Remember, not all browsers feel obliged to support includes(). Consider other methods or use a polyfill if necessary for older browser support.

Tools of the trade

Depending on your array-cracking needs, you might require alternative spoons:

You're looking for "some-thing"

(use Array.some()) If you need a boolean check across an array, some() is your champion:

const pokemon = ['Bulbasaur', 'Pikachu', 'Charizard']; const shortName = pokemon.some(name => name.length < 7); // Short names are easier to engrave on trophies

Can we find "the one" amongst the many?

(use Array.find()) Match an element to your criteria, or undefined if underwhelmed:

const pokemon = ['Bulbasaur', 'Pikachu', 'Charizard']; const fireType = pokemon.find(type => type === 'Charizard'); // Who needs a campfire with Charizard around?

Filter the noise

(use Array.filter()) Craft a new array with elements passing your arduous tests:

const pokemon = ['Bulbasaur', 'Pikachu', 'Charizard']; const longNames = pokemon.filter(name => name.length > 8); // Long names impress at parties

Deep dive into the ocean of arrays

While TypeScript super-powers JavaScript with type safety, improperly using methods like includes() and indexOf() can invite runtime errors.

TypeScript guards

Safeguard using TypeScript's type narrowing feature:

const mixedBag: (number | string)[] = ['apple', 5, 'mango']; if (typeof mixedBag[0] === 'string') { const foundFruit = mixedBag.includes('apple'); // I found the apple, do I win? }

Trespassing the boundary with "in"

Avoid the in operator in arrays; it's designed for property names (indexes), not array values.

TypeScript version play

Keep an eye on TypeScript's support for newer ECMAScript features which potentially depends on the TypeScript version you are using.