【问题标题】:Why does typescript show an error for my Array.filter parameters为什么打字稿对我的 Array.filter 参数显示错误
【发布时间】:2019-10-13 15:59:54
【问题描述】:

我正在使用 Array.prototype.filter 从对象中返回特定条目,但是 typescript 给我一个错误,“类型的参数 '(current: currentInterface) => boolean' is notassignable to parameter of type ' (value: [string, {}], index: number, array: [string, {}][]) => any'。 参数 'current' 和 'value' 的类型不兼容。”

current 是一个包含我要过滤的条目的对象。

我怎样才能让它工作,为什么它目前不能工作?

它似乎期望 current 是一个字符串,但是在普通 JS 中这不是必需的。

    interface currentInterface {
        firstName: string,
        lastName: string,
        [key: number]: any
    }

    //filter matching customers from list of customers by search term
    const matchingCustomers = Object.entries(state.customers).filter((current: currentInterface) => {
        let firstname = current[1].firstName.toLowerCase();
        let lastname = current[1].lastName.toLowerCase();
        let searchTerm = action.payload.searchTerm.toLowerCase();
        return firstname === searchTerm || lastname === searchTerm;
    });


Argument of type '(current: currentInterface) => boolean' is not assignable to parameter of type '(value: [string, {}], index: number, array: [string, {}][]) => any'.
  Types of parameters 'current' and 'value' are incompatible.
    Type '[string, {}]' is missing the following properties from type 'currentInterface': firstName, lastNamets(2345)

【问题讨论】:

    标签: arrays typescript filtering


    【解决方案1】:

    因为Object.entries 返回一个数组数组,但您正在分配一个接口。

    从您的代码来看,您似乎在寻找 Object.values 而不是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多