代码之家  ›  专栏  ›  技术社区  ›  David Hellsing

Typescript:使用map时带数组的数组失败

  •  1
  • David Hellsing  · 技术社区  · 6 年前
    type Point = [number, number]
    type Points = Array<Point>
    
    const ok: Points = [[0, 0]]
    const fail: Points = [0].map(() => [0, 0])
    

    类型“number[][]”不能分配给类型“[number,number][]”。

    有什么想法吗?

    Playground

    1 回复  |  直到 6 年前
        1
  •  4
  •   Sergiu Paraschiv    6 年前

    这是因为你怎么做的 map 是打字的。

    “官方”的定义是:

    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

    U 然后默认 U[] [] (同) Array ).

    问题是 [number, number] 是一个 子集 属于 地图 未具体说明 这意味着返回类型将是 大堆 .

    这两种类型不兼容,就会出现错误。

    解决方案是指定什么 地图 允许返回:

    const okToo: Points = [0].map<Point>(() => [0, 0])

    const notOk: Points = [0].map<Point>(() => [0, 0, 0])

    但在TypeScript2.6.1上是允许的。这是3.3中的一个错误,非常好。

    推荐文章