Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript cannot infer the correct type for response.body in got responses #2361

Open
2 tasks done
jasonwwl opened this issue Jul 8, 2024 · 2 comments
Open
2 tasks done

Comments

@jasonwwl
Copy link

jasonwwl commented Jul 8, 2024

Describe the bug

  • Node.js version: 20.15.0
  • OS & version: Ubuntu 20.04
  • Got version: 14.4.1
  • TypeScript version: 5.5.3

TypeScript cannot correctly infer the type for response.body in got responses when using generics.

Actual behavior

TypeScript infers the type of response.body as any despite specifying a generic type for the response, leading to loss of type safety.

image

Expected behavior

TypeScript should infer the type of response.body based on the generic type specified in the got request, ensuring type safety.

Code to reproduce

import got, { Method, Response } from 'got';

interface ApiResponse<T> {
  code: number;
  message: string;
  result: T;
  success: boolean;
  timestamp: number;
}

async function fetchData<R>(url: string, method: Method, data?: unknown): Promise<R> {
  try {
    const response: Response<ApiResponse<R>> = await got<ApiResponse<R>>({
      url,
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      json: data,
      responseType: 'json'
    });

    // this response.body is 'any'
    return response.body.result;
   
  } catch (e: any) {
    throw new Error(`Request failed: ${e.message}`);
  }
}

(async () => {
  const result = await fetchData<{ accessToken: string }>('https://example.com/api/token', 'POST', { key: 'value' });
  console.log(result.accessToken); // TypeScript should infer the correct type here
})();

Checklist

  • I have read the documentation.
  • I have tried my code with the latest version of Node.js and Got.
@wszgrcy
Copy link

wszgrcy commented Sep 25, 2024

I also have the same problem
image
The code is sourced from official instances https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md#events

@katsanva
Copy link
Contributor

katsanva commented Nov 2, 2024

@jasonwwl typescript@5.6.2 works fine, so this is not a problem with got itself, please upgrade on your side

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants