请原谅我的无知,但我正在尝试在 TypeScript 中实现提取,我一直在浏览这些示例,但无法编译。我是 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().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);
})
}
关于TypeScript Fetch response.Json<T> - 预期 0 个类型参数,但得到 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51341395/