TypeScript提取响应. -预期0个类型参数,但得到1个 [英] TypeScript Fetch response.Json<T> - Expected 0 type arguments, but got 1
问题描述
原谅我的无知,但是我试图在TypeScript中实现访存,并且我一直在浏览示例,但无法对其进行编译.我是TypeScript和Promise的新手,我找到了以下示例:
forgive my ignorance but I am trying to implement a fetch in TypeScript and I have been going through the examples but cannot get it to compile. I am new to TypeScript and Promise and I found this example:
我正在尝试实现这一点:
And I am trying to implement this:
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个.
[ts] Expected 0 type arguments, but got 1.
我不确定问题出在哪里,但是基本上我正在尝试实现一个包装API调用以返回项目数组的类,并且我已经尝试了async/await,但似乎没有任何工作.任何帮助将不胜感激.
I am not sure what the problem is but basically I am trying to implement a class which wraps the API calls to return an array of items and I have experimented with async/await and nothing seems to quite work. Any help would be greatly appreciated.
推荐答案
似乎签名不再存在,相反使用以下代码:
Seems that signature is not there anymore, Instead use this code:
response.json().then(data => data as T);
是的,这将为您返回强类型的数据. 下面是完整的代码片段.
Yeah, that will return you a strong typed data. Below the complete code snipped.
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提取响应. -预期0个类型参数,但得到1个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!