From 0a0427d9121b5eccf8214a47515ce47458cc231a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Vieira?= Date: Mon, 12 Aug 2019 17:50:20 +0100 Subject: [PATCH] Fix the `BeforeRequestHook` TypeScript type (#161) --- index.d.ts | 23 ++++++++++++++++++++--- index.test-d.ts | 1 + 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/index.d.ts b/index.d.ts index 5e01c435..429b7270 100644 --- a/index.d.ts +++ b/index.d.ts @@ -2,7 +2,7 @@ type _Omit = Pick>; -export type BeforeRequestHook = (options: Options) => void | Promise; +export type BeforeRequestHook = (options: NormalizedOptions) => void | Promise; export type AfterResponseHook = (response: Response) => Response | void | Promise; @@ -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 { - method?: 'get' | 'head' + method?: 'get' | 'head'; } interface OptionsWithBody extends KyOptions { @@ -241,6 +258,6 @@ declare const ky: { @returns A new Ky instance. */ extend(defaultOptions: Options): typeof ky; -} +}; export default ky; diff --git a/index.test-d.ts b/index.test-d.ts index 8390f705..b3858b31 100644 --- a/index.test-d.ts +++ b/index.test-d.ts @@ -48,6 +48,7 @@ ky(url, { beforeRequest: [ options => { expectType(options); + options.headers.set('foo', 'bar'); } ], afterResponse: [