sindresorhus / got

🌐 Human-friendly and powerful HTTP request library for Node.js
MIT License
14.27k stars 935 forks source link

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

Open jasonwwl opened 3 months ago

jasonwwl commented 3 months ago

Describe the bug

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

wszgrcy commented 1 month ago

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