【问题标题】:Visual Studio/Angular - Argument of type is not assignable to parameter type ObjectIterateeCustom<any[], boolean>Visual Studio/Angular - 类型参数不可分配给参数类型 ObjectIterateeCustom<any[], boolean>
【发布时间】:2018-11-25 08:56:15
【问题描述】:

我正在使用 typescript 3.8.3 和 loadash 进行 angular 5 项目。我使用 Visual Studio Code 作为我的编辑器。我最近将我的 Visual Studio Code 更新到了 1.24.0 版

更新后,我在 Visual Studio 代码中遇到了一些代码语法错误。这些错误不会导致任何编译器故障,而是在我的代码中显示为红色。我得到的一个恼人的问题是使用负载的以下代码:

let id: string = '122354';
let queue: any[] = records;
_.find(queue, {value: id}) // loads iteration function

我的错误信息

Argument of type '{ value: string; }' is not assignable to parameter of type 'ObjectIterateeCustom<any[], boolean>'.
Type '{ value: string; }' is not assignable to type 'ObjectIterator<any[], boolean>'.
Type '{ value: string; }' provides no match for the signature '(value: any, key: string, collection: any[]): boolean'.

不幸的是,我无法使用值类型定义队列。删除此语法错误的选项有哪些?提前致谢。

【问题讨论】:

    标签: angular typescript visual-studio-code lodash


    【解决方案1】:

    lodash's find method 有一个类似的类型定义

    find<T>(
            object: _.Dictionary<T>,
            iterator: _.ObjectIterator<T, boolean>,
            context?: any): T | undefined;
    

    注意 ObjectIterator 的类型 T。这意味着传递给迭代器的对象属性/值必须与作为object 参数传递的类型相匹配。

    换句话说,_.find(*[], {value: *, otherProp: *}) 的星号必须是相同的类型。

    试试

    let id: any= '122354';
    let queue: any[] = records;
    _.find(queue, {value: id})
    

    您还可以将as any 添加到该值。这会将id 转换为any 类型,匹配queue 的类型。

    let id: string = '122354';
    let queue: any[] = records;
    _.find(queue, {value: id as any})
    

    【讨论】:

      【解决方案2】:

      queue的结构是什么?

      _.find(queue, {value: id})

      尝试用函数替换{value: id}

      const someFn = (el) => {
       return el.id === id;
      }
      

      【讨论】:

        【解决方案3】:

        不要使用any类型,而是尝试放置一个带有属性值的接口

        let queue: Record[] = [];
        let record:Record=_.chain(queue).find({value:id}).value();
        

        【讨论】:

          【解决方案4】:

          只需显式声明类型参数T,而不是让它被推断:

          let id: string = '122354';
          let queue: any[] = records;
          _.find<string[]>(queue, {value: id});
          

          【讨论】:

            猜你喜欢
            • 2019-10-26
            • 2021-10-18
            • 1970-01-01
            • 2022-08-04
            • 2021-12-05
            • 2020-03-19
            • 2021-08-24
            • 2021-11-23
            • 2019-09-06
            相关资源
            最近更新 更多