TypeScript Fetch response.Json<T> - Expected 0 type arguments, but got 1

故事扮演 提交于 2020-01-03 08:49:08

问题


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:

How to use fetch in typescript

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>()
          })          
}

However the compiler shows the error:

[ts] Expected 0 type arguments, but got 1.

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.


回答1:


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);
      })          
}



回答2:


I found one problem with answer above. If you have JSON body like this

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

code above will return object with one key error and "{ "message" : "some message" }" So it's better to use

JSON.Stringify(data)


来源:https://stackoverflow.com/questions/51341395/typescript-fetch-response-jsont-expected-0-type-arguments-but-got-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!