Skip to content

Commit

Permalink
ignore redirects when inferring loader data types (#12527)
Browse files Browse the repository at this point in the history
  • Loading branch information
pcattori authored Dec 11, 2024
1 parent 7cd5c54 commit c9487e6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/khaki-gifts-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Ignore redirects when inferring loader data types
9 changes: 7 additions & 2 deletions packages/react-router/lib/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1367,7 +1367,12 @@ export interface TrackedPromise extends Promise<any> {
export type RedirectFunction = (
url: string,
init?: number | ResponseInit
) => Response;
) => Redirect;

// use a `unique symbol` to create a branded type
// https://egghead.io/blog/using-branded-types-in-typescript
declare const redirectSymbol: unique symbol;
export type Redirect = Response & { [redirectSymbol]: never };

/**
* A redirect response. Sets the status code and the `Location` header.
Expand All @@ -1389,7 +1394,7 @@ export const redirect: RedirectFunction = (url, init = 302) => {
return new Response(null, {
...responseInit,
headers,
});
}) as Redirect;
};

/**
Expand Down
8 changes: 6 additions & 2 deletions packages/react-router/lib/types/route-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type {
ClientLoaderFunctionArgs,
ClientActionFunctionArgs,
} from "../dom/ssr/routeModules";
import type { DataWithResponseInit } from "../router/utils";
import type { DataWithResponseInit, Redirect } from "../router/utils";
import type { Serializable } from "../server-runtime/single-fetch";
import type { Equal, Expect, Func, IsAny, Pretty } from "./utils";

Expand Down Expand Up @@ -44,11 +44,13 @@ type DataFrom<T> =

// prettier-ignore
type ClientData<T> =
T extends Redirect ? never :
T extends DataWithResponseInit<infer U> ? U :
T

// prettier-ignore
type ServerData<T> =
T extends Redirect ? never :
T extends DataWithResponseInit<infer U> ? Serialize<U> :
Serialize<T>

Expand Down Expand Up @@ -84,6 +86,7 @@ type __tests = [
| { data: string; b: Date; c: undefined }
>
>,
Expect<Equal<ServerDataFrom<() => { a: string } | Redirect>, { a: string }>>,

// ClientDataFrom
Expect<Equal<ClientDataFrom<any>, undefined>>,
Expand All @@ -105,5 +108,6 @@ type __tests = [
| { json: string; b: Date; c: () => boolean }
| { data: string; b: Date; c: () => boolean }
>
>
>,
Expect<Equal<ClientDataFrom<() => { a: string } | Redirect>, { a: string }>>
];

0 comments on commit c9487e6

Please sign in to comment.