【问题标题】:How to correctly define types for TS map, reducer, filter etc functions?如何正确定义 TS map、reducer、filter 等函数的类型?
【发布时间】:2021-03-21 17:21:20
【问题描述】:

当我尝试将正确的类型传递给内置 .map.filter 函数时,我的 TS 代码出现错误

当我这样做时:Object.values(league.games).map((game: Game) => { 我明白了

Argument of type '(game: Game) => { players: { rounds: PlayerRound[]; information: PlayerInformation; hasBeenEliminated: boolean; }[]; complete: boolean; id: string; leagueRound: number; }' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => { players: { rounds: PlayerRound[]; information: PlayerInformation; hasBeenEliminated: boolean; }[]; complete: boolean; id: string; leagueRound: number; }'.
  Types of parameters 'game' and 'value' are incompatible.

但我不明白如何正确地给它正确的类型?我对它的要求有点困惑

我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs typescript types


    【解决方案1】:

    您可以在声明变量后立即键入变量。那么数组中的单个元素也将是正确的类型。

    https://codesandbox.io/s/epic-almeida-opq9d?file=/src/index.ts

    【讨论】:

      【解决方案2】:

      您可能需要将通用 T 提供给 Object.values<T>,以便其返回类型为 - T[]

      values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];
      

      解决方案

      Object.values<Game>(league.games).map((game) => { ... })
      
      //        values will be Game[] ^       ^ game will be of type Game
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-28
        • 2018-01-02
        • 1970-01-01
        • 2023-03-16
        • 2021-12-19
        • 2021-12-11
        • 2021-09-20
        相关资源
        最近更新 更多