Skip to content

Latest commit

 

History

History
177 lines (107 loc) · 8.9 KB

typescript.md

File metadata and controls

177 lines (107 loc) · 8.9 KB

> Back to homepage

TypeScript

Got is fully written in TypeScript, so the integration is seamless.
Furthermore, types have saved Got from many bugs and inconsistencies.

Wrapping Got in an API client

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); // boolean

Note:

  • Use .json<T>() to get RequestPromise<T> with the body-only response.
  • Use .json(schema) to validate the body with a Standard Schema validator and get the output type of the schema.
  • Use .buffer() or .text() for other response types.
  • Without calling these methods, you'll get RequestPromise<Response<T>>.
  • Use signal and AbortController to abort requests.

Types

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.