Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type {
RedirectFunction,
ShouldRevalidateFunction,
V7_FormMethod,
TypedResponse,
} from "./utils";

export {
Expand Down
19 changes: 15 additions & 4 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <Data>(
export type JsonFunction = <Data extends unknown>(
data: Data,
init?: number | ResponseInit
) => Response;
) => TypedResponse<Data>;

export type TypedResponse<T extends unknown = unknown> = Omit<
Response,
"json"
> & {
json(): Promise<T>;
};

/**
* 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;
Expand Down Expand Up @@ -1418,11 +1427,13 @@ export const defer: DeferFunction = (data, init = {}) => {
export type RedirectFunction = (
url: string,
init?: number | ResponseInit
) => Response;
) => TypedResponse<never>;

/**
* 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;
Expand All @@ -1438,7 +1449,7 @@ export const redirect: RedirectFunction = (url, init = 302) => {
return new Response(null, {
...responseInit,
headers,
});
}) as TypedResponse<never>;
};

/**
Expand Down