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;
}
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.
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.
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.
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.
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With