Skip to content

Commit

Permalink
Fix the BeforeRequestHook TypeScript type (#161)
Browse files Browse the repository at this point in the history
  • Loading branch information
joaovieira authored and sindresorhus committed Aug 12, 2019
1 parent 00266ea commit 0a0427d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
23 changes: 20 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

type _Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

export type BeforeRequestHook = (options: Options) => void | Promise<void>;
export type BeforeRequestHook = (options: NormalizedOptions) => void | Promise<void>;

export type AfterResponseHook = (response: Response) => Response | void | Promise<Response | void>;

Expand Down Expand Up @@ -92,8 +92,25 @@ interface KyOptions extends RequestInit {
onDownloadProgress?: (progress: DownloadProgress, chunk: Uint8Array) => void;
}

/**
Normalized options passed to the `fetch` call and the beforeRequest hooks.
*/
interface NormalizedOptions extends RequestInit {
// Extended from `RequestInit`, but ensured to be set (not optional).
method: RequestInit['method'];
credentials: RequestInit['credentials'];

// Extended from custom `KyOptions`, but ensured to be set (not optional).
retry: KyOptions['retry'];
prefixUrl: KyOptions['prefixUrl'];
onDownloadProgress: KyOptions['onDownloadProgress'];

// New type.
headers: Headers;
}

interface OptionsWithoutBody extends _Omit<KyOptions, 'body' | 'json'> {
method?: 'get' | 'head'
method?: 'get' | 'head';
}

interface OptionsWithBody extends KyOptions {
Expand Down Expand Up @@ -241,6 +258,6 @@ declare const ky: {
@returns A new Ky instance.
*/
extend(defaultOptions: Options): typeof ky;
}
};

export default ky;
1 change: 1 addition & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ ky(url, {
beforeRequest: [
options => {
expectType<Object>(options);
options.headers.set('foo', 'bar');
}
],
afterResponse: [
Expand Down

0 comments on commit 0a0427d

Please sign in to comment.