代码之家  ›  专栏  ›  技术社区  ›  Max Heiber

“参数类型“\u0”和“值”不兼容”是错误吗?

  •  0
  • Max Heiber  · 技术社区  · 7 年前

    此类型签入 TypeScript Playground ,但在v3.1.6上失败:

    function head([a]) {
      return a;
    }
    
    const x: number[] = [[1], [2]].map(head)
    

    错误消息:

    server/src/mock-resolvers/mock-data.ts(549,36): error TS2345: Argument of type '([a]: [any]) => any' is not assignable to parameter of type '(value: number[], index: number, array: number[][]) => any'.
      Types of parameters '__0' and 'value' are incompatible.
        Type 'number[]' is not assignable to type '[any]'.
          Property '0' is missing in type 'number[]'.
    

    这是虫子吗?我不明白错误信息,也不知道代码有什么问题。

    对类型更具体一点也没有帮助,如果函数定义如下,我会遇到类似的错误:

    function head([a, _b]: [number, number]): number {
      return a;
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Titian Cernicova-Dragomir    7 年前

    如果启用 strictFunctionTypes 在操场上。您可以阅读有关此选项的更多信息 here 但它的要点是,它消除了函数的双方差。

    在你的情况下数组 [[1], [2]] Array<[number]> ,而是键入为 Array<number[]> ,因为typescript不会为数组文本推断元组类型,除非它被指示这样做。这会导致一个错误,因为函数是显式接受元组类型的 [any] any

    最简单的解决方案是显式指定数组的类型:

    function head([a] : [number]) { // type is not required but it's best to not leave implict any 
      return a;
    }
    
    const data: Array<[number]> = [[1], [2]]
    const x: number[] = data.map(head)
    

    function tuple<T extends any[]>(...a: T) {
      return a;
    }
    
    const x: number[] = [tuple(1), tuple(2)].map(head)
    

    function tupleArray<T extends [any]|any[]>(...a: T[]) {
      return a;
    }
    
    const x: number[] = tupleArray([1], [2]).map(head)
    
    推荐文章