简体   繁体   English

TypeScript相当于JavaScript包括()

[英]TypeScript equivalent of JavaScript includes()

Getting a TypeScript error using includes on an array element. 使用包含在数组元素上的TypeScript错误。 Of course once compiled down to js it works fine but I still get the following TypeScript error: 当然,一旦编译成js它工作正常但我仍然得到以下TypeScript错误:

Property 'includes' does not exist on type 'boolean[]' 类型'boolean []'上不存在属性'includes'

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;
}

As far as fixing the compilation error goes, fixed the compilation issue was adding es2016 to the lib option in my tsconfig.json . 至于修复编译错误,修复编译问题是将es2016添加到我的tsconfig.jsonlib选项。 This adds the necessary declaration of includes on arrays. 这为数组添加了必要的includes声明。

I tried with TypeScript 2.1.4 the suggested fix of replacing boolean[] with Array<boolean> . 我尝试使用TypeScript 2.1.4 建议使用Array<boolean>替换boolean[] It made no difference whatsoever. 它没有任何区别。 Logically, it shouldn't make a difference because boolean[] and Array<boolean> are the same thing . 从逻辑上讲,它应该没有区别,因为boolean[]Array<boolean> 是相同的


This being said, I concur with torazaburo that the OP's code should be implemented as: 话虽如此,我同意torazaburo认为OP的代码应该实现为:

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. 除了删除不必要的逻辑之外,这还有一个优点,即一旦回调返回一个假值, every停止都会检查数组。 There's no point inspecting the rest because the return value will necessarily be false as soon as the callback returns a falsy value. 检查其余部分是没有意义的,因为一旦回调返回一个false值,返回值必然是false 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!! 如果第一个元素未通过测试,那么它将不必要地检查阵列的其余部分!

@echonax's comment worked for me. @ echonax的评论对我有用。

validAttrs() {
  let valid: Array<boolean> = this.required.map((value, index) => {
    if(this.elm.nativeElement.getAttribute(value) === null) {
      return false;
    };
    return true;
  });
  return valid.includes(false) ? false : true;
}

You don't even need includes for what you are trying to do. 您甚至不需要includes您正在尝试的内容。 Your code can simply be 你的代码可以简单

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

This also has the advantage that it will stop checking the minute it finds the first null value. 这也有一个好处,它将停止检查它找到第一个空值的分钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM