Skip to content
Myr

Fix `hooks: {x: undefined}` and `signal: undefined` failing to type-check with `exactOptionalPropertyTypes`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent c6c5dbf · Browse files · 5 files+35 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+35 added−14 removed

  • other:+35 added−14 removed

5 files+35 added−14 removed

modified:source/core/Ky.ts+1 added-1 removed
451 unmodified lines
452 ) {453 this.#options.headers.delete('content-type');454 }455456 this.request = new globalThis.Request(this.#input, this.#options);456 this.request = new globalThis.Request(this.#input, this.#options as RequestInit);457458 if (hasSearchParameters(this.#options.searchParams)) {459 const url = new URL(this.request.url);460 const deleted = (this.#options.searchParams as any)?.[deletedParametersSymbol] as Set<string> | undefined;
775 unmodified lines
modified:source/types/hooks.ts+10 added-5 removed
111 unmodified lines
112 ```113114 @default []115 */116 init?: InitHook[];116 init?: InitHook[] | undefined;117118 /**119 This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.120
42 unmodified lines
163 ```164165 @default []166 */167 beforeRequest?: BeforeRequestHook[];167 beforeRequest?: BeforeRequestHook[] | undefined;168169 /**170 This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and retry count. You could, for example, modify `request.headers` here.171
73 unmodified lines
245 ```246247 @default []248 */249 beforeRetry?: BeforeRetryHook[];249 beforeRetry?: BeforeRetryHook[] | undefined;250251 /**252 This hook enables you to modify any error right before it is thrown. The hook function receives a state object with the current request, the normalized Ky options, the error, and retry count, and should return an `Error` instance.253
33 unmodified lines
287 }288 });289 ```290 */291 beforeError?: BeforeErrorHook[];291 beforeError?: BeforeErrorHook[] | undefined;292293 /**294 This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).295
64 unmodified lines
360 }361 });362 ```363 */364 afterResponse?: AfterResponseHook[];364 afterResponse?: AfterResponseHook[] | undefined;365};366367/**368Hooks after normalization: every hook type is present as an array.369*/370export type NormalizedHooks = {[Key in keyof Hooks]-?: NonNullable<Hooks[Key]>};
modified:source/types/options.ts+11 added-3 removed
1import type {LiteralUnion, Required} from './common.js';2import type {Hooks} from './hooks.js';2import type {Hooks, NormalizedHooks} from './hooks.js';3import type {RetryOptions} from './retry.js';45// eslint-disable-next-line unicorn/prevent-abbreviations6export type SearchParamsInit = string | string[][] | Record<string, string> | URLSearchParams | undefined;
396 unmodified lines
403404/**405Options are the same as `window.fetch`, except for the KyOptions406*/407export interface Options extends KyOptions, Omit<RequestInit, 'headers'> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.407export interface Options extends KyOptions, Omit<RequestInit, 'headers' | 'signal'> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.408 /**409 HTTP method used to make the request.410411 Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.
35 unmodified lines
447 //=> true448 ```449 */450 headers?: KyHeadersInit;451452 /**453 An `AbortSignal` to abort the request.454455 When extending an instance, signals are combined. Use `replaceOption(signal)` to replace inherited signals, or `signal: undefined` to remove them.456 */457 // eslint-disable-next-line @typescript-eslint/no-restricted-types458 signal?: AbortSignal | null | undefined;459}460461type NormalizedRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;462
1 unmodified line
464 Omit<Options, 'hooks' | 'retry' | 'context' | 'throwHttpErrors'>,465 'fetch' | 'prefix' | 'timeout' | 'totalTimeout'466> & {467 headers: Required<Headers>;460 hooks: Required<Hooks>;468 hooks: NormalizedHooks;469 retry: NormalizedRetryOptions;470 prefix: string;471 context: Record<string, unknown>;472 throwHttpErrors: boolean | ((status: number) => boolean);
21 unmodified lines
modified:source/utils/merge.ts+5 added-5 removed
1import type {KyHeadersInit, Options} from '../types/options.js';2import type {Hooks} from '../types/hooks.js';2import type {Hooks, NormalizedHooks} from '../types/hooks.js';3import {supportsAbortSignal} from '../core/constants.js';4import {isObject} from './is.js';56const replaceSymbol: unique symbol = Symbol('replaceOption');
122 unmodified lines
129130 return mergeHeaders(source1, source2);131};132133function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): Required<Hooks>[K] {133function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {134 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {135 return [];136 }137138 // A single hook type can be wrapped in `replaceOption()` to replace only that array instead of the whole `hooks` object.139 const {isReplace, value} = getReplaceState(incoming[property]);140 if (isReplace) {141 return [...(value ?? [])] as Required<Hooks>[K];141 return [...(value ?? [])] as NormalizedHooks[K];142 }143144 return deepMerge<Required<Hooks>[K]>(original[property] ?? [], value ?? []);144 return deepMerge<NormalizedHooks[K]>(original[property] ?? [], value ?? []);145}146147export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): Required<Hooks> => (147export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => (148 {149 init: newHookValue(original, incoming, 'init'),150 beforeRequest: newHookValue(original, incoming, 'beforeRequest'),151 beforeRetry: newHookValue(original, incoming, 'beforeRetry'),
197 unmodified lines
modified:test-d/normalized-options.ts+8 added