Got is fully written in TypeScript, so the integration is seamless.
Furthermore, types have saved Got from many bugs and inconsistencies.
You can wrap Got in a type-safe API client while preserving all Got features including progress/events support:
import got, {type RequestPromise, type OptionsOfJSONResponseBody, type Progress} from 'got';
interface FizzBuzz {
fizz: boolean;
buzz: boolean;
}
class ExampleAPI {
private client = got.extend({
prefixUrl: 'https://api.example.com'
});
isFizzBuzz(number: number): RequestPromise<FizzBuzz> {
return this.client.get('fizzbuzz', {
searchParams: {number},
responseType: 'json',
resolveBodyOnly: true
}).json<FizzBuzz>();
}
// For more complex cases, you can specify options
getData(id: string, options?: OptionsOfJSONResponseBody): RequestPromise<FizzBuzz> {
return this.client.get(`data/${id}`, {
...options,
responseType: 'json',
resolveBodyOnly: true
}).json<FizzBuzz>();
}
}
const api = new ExampleAPI();
// The promise has full type support
const promise = api.isFizzBuzz(20);
// Event methods are available
promise.on('downloadProgress', (progress: Progress) => {
console.log(progress.percent);
});
// The result is properly typed
const result = await promise;
console.log(result.fizz); // boolean
console.log(result.buzz); // booleanNote:
- Use
.json<T>()to getRequestPromise<T>with the body-only response.- Use
.buffer()or.text()for other response types.- Without calling these methods, you'll get
RequestPromise<Response<T>>.- Use
signalandAbortControllerto abort requests.
Here's a list of types that Got exports:
Note:
- The list may be incomplete. If you find a type is missing, please open an issue about it.