TypeScript数组的find()方法说:“没有重载匹配此调用”

时间:2020-01-11 17:55:41

标签: arrays angular typescript

问题陈述

我正在为数组使用TypeScript的find()方法,但是当我输入value时,它不起作用并显示“没有重载匹配此调用”。


代码

addOption(event: MatChipInputEvent) {
    const input = event.input;
    const value = event.value;

    // Makes sure that the same element is not inserted in the the options array
    if (value !== this.options.find(value)) {
      // Add our option
      if ((value || '').trim()) {
        this.options.push(value.trim());
      }
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

代码说明

如您所见,我在 first find条件中使用if方法来检查并防止同一元素进入数组。您在此处看到的值带有红色下划线,并显示错误“此调用无重载”。我似乎在语法上所做的一切都正确,但是错误仍然存​​在。


实际结果

find方法给我错误,“没有重载匹配此调用”,并且不接受参数中的值。


预期结果

用于获取值并在数组中查找元素的find方法。

1 个答案:

答案 0 :(得分:2)

您应该使用find而不是includes

if (!this.options.includes(value)) {

如果您确实要使用find,可以按照以下步骤操作:

if (this.options.find(o => o === value) == undefined) {