From 07917876cca85e8d7ba7abb57126d41c59162a95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20De=20Boey?= Date: Sat, 3 Dec 2022 01:31:33 +0100 Subject: [PATCH] feat(router): add type safety to `json` & `redirect` functions --- packages/router/index.ts | 1 + packages/router/utils.ts | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/router/index.ts b/packages/router/index.ts index 3d4fea9620..1f2a8fe7b5 100644 --- a/packages/router/index.ts +++ b/packages/router/index.ts @@ -24,6 +24,7 @@ export type { RedirectFunction, ShouldRevalidateFunction, V7_FormMethod, + TypedResponse, } from "./utils"; export { diff --git a/packages/router/utils.ts b/packages/router/utils.ts index 0b8b18d8c7..f7f7628e60 100644 --- a/packages/router/utils.ts +++ b/packages/router/utils.ts @@ -1197,14 +1197,23 @@ export const normalizeSearch = (search: string): string => export const normalizeHash = (hash: string): string => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; -export type JsonFunction = ( +export type JsonFunction = ( data: Data, init?: number | ResponseInit -) => Response; +) => TypedResponse; + +export type TypedResponse = Omit< + Response, + "json" +> & { + json(): Promise; +}; /** * This is a shortcut for creating `application/json` responses. Converts `data` * to JSON and sets the `Content-Type` header. + * + * @see https://reactrouter.com/fetch/json */ export const json: JsonFunction = (data, init = {}) => { let responseInit = typeof init === "number" ? { status: init } : init; @@ -1418,11 +1427,13 @@ export const defer: DeferFunction = (data, init = {}) => { export type RedirectFunction = ( url: string, init?: number | ResponseInit -) => Response; +) => TypedResponse; /** * A redirect response. Sets the status code and the `Location` header. * Defaults to "302 Found". + * + * @see https://reactrouter.com/fetch/redirect */ export const redirect: RedirectFunction = (url, init = 302) => { let responseInit = init; @@ -1438,7 +1449,7 @@ export const redirect: RedirectFunction = (url, init = 302) => { return new Response(null, { ...responseInit, headers, - }); + }) as TypedResponse; }; /**