elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.79k stars 96 forks source link

Issues with type inference on method .res #143

Closed giulianovarriale closed 2 years ago

giulianovarriale commented 2 years ago

Hello. First, thanks for creating this package. Awesome job!

I was creating a service to perform a request and based on the success status, do something else. Here is a pseudo code that simulates what I'm doing:

import wretch from "wretch";

interface IUser {
  name: string;
  email: string;
}

const api = wretch().url("https://some-service/api");

export function createUser(user: IUser): Promise<IUser> {
  return api
    .url("/users")
    .post(user)
    .res<IUser>((response) => {
      if (response.status === 204) {
        // do something
      }

      return response.json();
    });
}

For some reason, I'm not able to proper type the .res block. With the code above, I get the following error:

Argument of type '(response: WretcherResponse) => Promise<any>' is not assignable to parameter of type '(type: WretcherResponse) => IUser'.
  Type 'Promise<any>' is missing the following properties from type 'IUser': name, email

I've tried setting the type in many different ways but I can't get ride of the error. Am I doing something wrong or the type inference is not properly working for this block?

elbywan commented 2 years ago

Hey @giulianovarriale,

Hello. First, thanks for creating this package. Awesome job!

Thanks! πŸ‘

Am I doing something wrong or the type inference is not properly working for this block?

Nope, you are not doing anything wrong πŸ˜‰. Type inference for "thenable" functions was notoriously hard when wretch was written, several years ago.

But now, with typescript 4.5+ and the introduction of the Awaited helper it is way easier.

I just released a new version which improves the types for .res and other parser methods, which should now properly type the sample you posted.

Feel free to reopen otherwise, and thanks for reporting the issue in the first place πŸ™‡.

giulianovarriale commented 2 years ago

Wow, that was a quick response and fix! Nice. I will check if everything works properly. Thanks for sharing about the new API from typescript btw. Very handy.