Skip to content

Commit 0791787

Browse files
committed
feat(router): add type safety to json & redirect functions
1 parent 95a295c commit 0791787

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

packages/router/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export type {
2424
RedirectFunction,
2525
ShouldRevalidateFunction,
2626
V7_FormMethod,
27+
TypedResponse,
2728
} from "./utils";
2829

2930
export {

packages/router/utils.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,14 +1197,23 @@ export const normalizeSearch = (search: string): string =>
11971197
export const normalizeHash = (hash: string): string =>
11981198
!hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
11991199

1200-
export type JsonFunction = <Data>(
1200+
export type JsonFunction = <Data extends unknown>(
12011201
data: Data,
12021202
init?: number | ResponseInit
1203-
) => Response;
1203+
) => TypedResponse<Data>;
1204+
1205+
export type TypedResponse<T extends unknown = unknown> = Omit<
1206+
Response,
1207+
"json"
1208+
> & {
1209+
json(): Promise<T>;
1210+
};
12041211

12051212
/**
12061213
* This is a shortcut for creating `application/json` responses. Converts `data`
12071214
* to JSON and sets the `Content-Type` header.
1215+
*
1216+
* @see https://reactrouter.com/fetch/json
12081217
*/
12091218
export const json: JsonFunction = (data, init = {}) => {
12101219
let responseInit = typeof init === "number" ? { status: init } : init;
@@ -1418,11 +1427,13 @@ export const defer: DeferFunction = (data, init = {}) => {
14181427
export type RedirectFunction = (
14191428
url: string,
14201429
init?: number | ResponseInit
1421-
) => Response;
1430+
) => TypedResponse<never>;
14221431

14231432
/**
14241433
* A redirect response. Sets the status code and the `Location` header.
14251434
* Defaults to "302 Found".
1435+
*
1436+
* @see https://reactrouter.com/fetch/redirect
14261437
*/
14271438
export const redirect: RedirectFunction = (url, init = 302) => {
14281439
let responseInit = init;
@@ -1438,7 +1449,7 @@ export const redirect: RedirectFunction = (url, init = 302) => {
14381449
return new Response(null, {
14391450
...responseInit,
14401451
headers,
1441-
});
1452+
}) as TypedResponse<never>;
14421453
};
14431454

14441455
/**

0 commit comments

Comments
 (0)