Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript equivalent of JavaScript includes()

Getting a TypeScript error using includes on an array element. Of course once compiled down to js it works fine but I still get the following TypeScript error:

Property 'includes' does not exist on type 'boolean[]'

Code:

validAttrs() {
  let valid: boolean[] = this.required.map((value, index) => {
    if(this.elm.nativeElement.getAttribute(value) === null) {
      return false;
    };
    return true;
  });
  return valid.includes(false) ? false : true;
}
like image 883
John williams Avatar asked Dec 21 '16 10:12

John williams


People also ask

What can be used instead of includes in JavaScript?

indexOf() The Array#indexOf() function is a common alternative to includes() . The indexOf() function returns the first index in the array at which it found valueToFind , or -1 otherwise.

What is the use of includes in TypeScript?

The includes() method determines whether an array contains a specified element. This method returns true if the array contains the element, and false if not.

How do I check if a list contains an item in TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise.

Can I use includes JavaScript?

includes() used as a generic methodincludes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.


1 Answers

As far as fixing the compilation error goes, fixed the compilation issue was adding es2016 to the lib option in my tsconfig.json. This adds the necessary declaration of includes on arrays.

I tried with TypeScript 2.1.4 the suggested fix of replacing boolean[] with Array<boolean>. It made no difference whatsoever. Logically, it shouldn't make a difference because boolean[] and Array<boolean> are the same thing.


This being said, I concur with torazaburo that the OP's code should be implemented as:

validAttrs() {
  return this.required.every(value => this.elm.nativeElement.getAttribute(value) !== null);
}

Besides removing unnecessary logic, this also has the advantage that every stops inspecting the array as soon as the callback returns a falsy value. There's no point inspecting the rest because the return value will necessarily be false as soon as the callback returns a falsy value. On the other hand, the implementation in the question will always perform the test on all elements the of array. If the very first element fails the test, then it will inspect the rest of the array needlessly!!

like image 66
Louis Avatar answered Sep 26 '22 00:09

Louis