Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 552
user351711 Avatar asked Jul 14 '18 16:07

user351711


2 Answers

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);
      })          
}
like image 56
Marco Medrano Avatar answered Nov 03 '22 03:11

Marco Medrano


Got the same error with Express when I forgot this import:

import { Request, Response } from 'express';

The complete example becomes:

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

export const someMethod = async (req: Request, res: Response) => {
   // ...
}
like image 2
FloatingRock Avatar answered Nov 03 '22 05:11

FloatingRock