Sub topic 8
Type-safe route modules with generated types
This chapter assumes you know TypeScript basics, can read a route module with a loader and a default component, and have an app/routes.ts file like the one from the earlier chapters. You will learn how React Router generates types for each route, how to use them, and which errors come up most often.
Why generated types exist
A route module's types depend on things outside the file itself:
- The URL pattern in
app/routes.tsdecides whichparamsexist. - The parent routes decide what the route renders inside.
- The return value of
loaderandactiondecides what the component receives.
A hand-written type could drift from any of these. React Router instead reads your route config and your route modules, then writes a type file for each route. You import types from that file and the compiler checks your code against the real route setup.
Where the types come from
For every route module, React Router generates a file named +types/<module-name>.d.ts next to it, inside a hidden .react-router/types folder that mirrors your app folder. You never open or edit these files. You import them with a relative path as if they sat beside your module:
import type { Route } from "./+types/detail";The import resolves because tsconfig.json lists rootDirs, which makes TypeScript treat the real folder and the generated folder as one. A project created from the official template already has this setup:
{
"include": [
".react-router/types/**/*",
"app/**/*",
"app/**/.server/**/*",
"app/**/.client/**/*"
],
"compilerOptions": {
"rootDirs": [".", "./.react-router/types"],
"verbatimModuleSyntax": true
}
}The generated files are created when you run react-router dev or react-router build. You can also generate them on demand with npx react-router typegen. Use typegen in CI before tsc, because a fresh checkout has no .react-router folder yet.
{
"scripts": {
"typecheck": "react-router typegen && tsc"
}
}What the `Route` namespace contains
Each generated file exports a Route namespace. These are the members you will use most:
| Type | Used for |
|---|---|
| `Route.LoaderArgs` | Argument of `loader`, with typed `params` |
| `Route.ActionArgs` | Argument of `action`, with typed `params` |
| `Route.ComponentProps` | Props of the default export: `loaderData`, `actionData`, `params`, `matches` |
| `Route.ErrorBoundaryProps` | Props of `ErrorBoundary`, including `error` |
| `Route.MetaArgs` | Argument of `meta`, including `data` |
| `Route.ClientLoaderArgs` | Argument of `clientLoader` |
Because the names are the same in every module, you copy the same pattern into each file and only the import path changes.
Typed params
The params object is built from the route's path. Take this entry from app/routes.ts:
route("contacts/:contactId", "routes/contacts/detail.tsx")In detail.tsx, Route.LoaderArgs["params"] is { contactId: string }. A typo such as params.contactID fails to compile.
Optional segments and splats are typed too. A path ending in /* gives you params["*"], and an optional segment like :lang? gives lang: string | undefined. Params are always strings, so convert them yourself:
import type { Route } from "./+types/detail";
export async function loader({ params }: Route.LoaderArgs) {
const id = Number(params.contactId);
if (!Number.isInteger(id)) {
throw new Response("Bad id", { status: 400 });
}
return { id };
}Typed loader data
loaderData in the component is inferred from what the loader returns. You do not write a type annotation for it:
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw new Response("Not found", { status: 404 });
}
return { contact, fetchedAt: new Date() };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
const { contact, fetchedAt } = loaderData;
return (
<p>
{contact.name}, loaded at {fetchedAt.toISOString()}
</p>
);
}React Router serializes loader data with its own format, so values such as Date, Map, Set, and promises keep their types across the network. The generated types account for this. This differs from plain JSON.stringify, which would turn a Date into a string.
Two details help you avoid surprises:
- Throwing inside the
loaderdoes not add to the inferred return type. The component only sees the success shape, because the error path goes toErrorBoundary. - If you return
data(...)with a status code, the inferred type is the data you passed in, not the wrapper.
Typed action data
actionData works the same way and is typed as undefined until a submission has returned. That is why the earlier form example reads actionData?.error. When an action returns different shapes, actionData becomes a union:
import { data, redirect } from "react-router";
import type { Route } from "./+types/new";
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return data({ error: "Name is required" }, { status: 400 });
}
return redirect("/contacts");
}
export default function NewContact({ actionData }: Route.ComponentProps) {
return <p>{actionData?.error}</p>;
}A redirect does not appear in actionData, since the browser leaves the page. Only the { error: string } shape remains.
Typing parent data and matches
Route.ComponentProps also includes matches, an array describing every active route from the root down to the current one, each with its loaderData. Use it when a child needs data from a parent, but prefer to pass data through a loader of its own when you can, because matches couples the child to the parent's position.
Reading types for other hooks
Hooks outside the route module cannot import the generated Route type. You have two choices:
- Pass
loaderDatadown as a prop and type the prop from the parent. - Use
useRouteLoaderDatawith a type import of the other route's module:useRouteLoaderData<typeof import("~/root").loader>("root").
Common errors
- Cannot find module
./+types/detail. The types have not been generated, orrootDirsis missing fromtsconfig.json. Runnpx react-router typegen, then restart the TypeScript server in your editor. - A route works at runtime but has no
params. The route is missing fromapp/routes.ts, so no type file exists for it. Add it and run typegen again. - Types look stale after renaming a route file. Restart
react-router dev. The generator watches the route config, but editors sometimes cache old results. - Importing a
.servermodule in a type position leaks nothing. Aimport typeline is erased, so it is safe. A value import of a server module into client code is the real problem, covered in the next chapter.
How the pieces fit
Exercise
A route is registered as route("posts/:postId/comments/:commentId", "routes/comment.tsx"). What is the type of params in Route.LoaderArgs, and why must you still validate it before using it as a number?
Show answer
It is { postId: string; commentId: string }. URL segments are always strings, and the type only guarantees the names exist, not that the text is numeric. Convert with Number(...) and reject bad values, for example by throwing a 400 response.
Exercise
Your editor reports "Cannot find module './+types/list'" on a fresh clone, although routes/contacts/list.tsx is listed in app/routes.ts. Name two things to check and the command that fixes the common case.
Show answer
Check that .react-router/types has been generated and that tsconfig.json has rootDirs including ./.react-router/types (and include covering it). Running npx react-router typegen generates the files, and restarting the TypeScript server refreshes the editor.