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

var array: Array<string> = ['one', 'two', 'abc'];

The same as in JavaScript, using Array.prototype.indexOf():

console.log(array.indexOf('abc') > -1);

Or using ECMAScript 2016 Array.prototype.includes():


However, you wouldn’t usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => === 'bar')); // true
console.log(arr.filter(e => === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]





Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store