TypeScript Fetch response.Json <T>-预期0个类型参数,但得到1个

use*_*711 7 typescript fetch-api

原谅我的无知,但是我试图在TypeScript中实现抓取,并且我一直在浏览示例,但无法对其进行编译。我是TypeScript和Promise的新手,我找到了以下示例:

如何在打字稿中使用提取

我正在尝试实现这一点:

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

但是,编译器显示错误:

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

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

Flo*_*ock 7

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

import { Request, Response } from 'express';
Run Code Online (Sandbox Code Playgroud)

完整的例子变成:

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

export const someMethod = async (req: Request, res: Response) => {
   // ...
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ano 5

似乎签名不再存在,而是使用以下代码:

response.json().then(data => data as T);
Run Code Online (Sandbox Code Playgroud)

是的,那将为您返回强类型数据。下面完整的代码被摘录。

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);
      })          
}
Run Code Online (Sandbox Code Playgroud)