【问题标题】:TypeScript Fetch response.Json<T> - Expected 0 type arguments, but got 1TypeScript Fetch response.Json<T> - 预期 0 个类型参数,但得到 1
【发布时间】:2023-04-06 18:27:01
【问题描述】:

请原谅我的无知,但我正在尝试在 TypeScript 中实现 fetch 并且我一直在浏览示例但无法编译它。我是 TypeScript 和 Promise 的新手,我找到了这个例子:

How to use fetch in typescript

我正在尝试实现这一点:

private api<T>(url: string): Promise<T> {
        return fetch(url)
          .then(response => {
            if (!response.ok) {
              throw new Error(response.statusText)
            }
            return response.json<T>()
          })          
}

但是编译器显示错误:

[ts] 预期的类型参数为 0,但得到了 1。

我不确定问题出在哪里,但基本上我正在尝试实现一个类,它包装 API 调用以返回一个项目数组,并且我已经尝试了 async/await,但似乎没有什么能奏效。任何帮助将不胜感激。

【问题讨论】:

  • response.json() 不是通用方法,但您正在尝试使其通用
  • 也许您正在寻找类似的东西来将其转换为特定类型的 Promise 例如 return response.json() as Treturn &lt;T&gt;response.json()

标签: typescript fetch-api


【解决方案1】:

当我忘记此导入时,Express 遇到了同样的错误:

import { Request, Response } from 'express';

完整的例子变成:

// controllers/my-controller.ts
import { Request, Response } from 'express';

export const someMethod = async (req: Request, res: Response) => {
   // ...
}

【讨论】:

    【解决方案2】:

    我在上面的答案中发现了一个问题。 如果你有这样的 JSON 正文

    { "error" : "{ "message" : "some message" }" }
    

    上面的代码将返回带有一键错误和 "{ "message" : "some message" }" 的对象 所以最好用

    JSON.Stringify(data)
    

    【讨论】:

      【解决方案3】:

      似乎签名不再存在,改为使用此代码:

      response.json().then(data => data as T);
      

      是的,这将返回一个强类型数据。 下面是完整的代码片段。

      private api<T>(url: string): Promise<T> {
          return fetch(url)
            .then(response => {
              if (!response.ok) {
                throw new Error(response.statusText)
              }
              return response.json().then(data => data as T);
            })          
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多