UNPKG

2.4 kB Markdown View Raw
1---
2title: Type Safety
3---
4
5# Type Safety
6
7[MODES: framework]
8
9If you haven't done so already, check out our guide for [setting up type safety][route-module-type-safety] in a new project.
10
11React Router generates types for each route in your app to provide type safety for the route module exports.
12
13For example, let's say you have a `products/:id` route configured:
14
15```ts filename=app/routes.ts
16import {
17 type RouteConfig,
18 route,
19} from "@react-router/dev/routes";
20
21export default [
22 route("products/:id", "./routes/product.tsx"),
23] satisfies RouteConfig;
24```
25
26You can import route-specific types like so:
27
28```tsx filename=app/routes/product.tsx
29import type { Route } from "./+types/product";
30// types generated for this route 👆
31
32export function loader({ params }: Route.LoaderArgs) {
33 // 👆 { id: string }
34 return { planet: `world #${params.id}` };
35}
36
37export default function Component({
38 loaderData, // 👈 { planet: string }
39}: Route.ComponentProps) {
40 return <h1>Hello, {loaderData.planet}!</h1>;
41}
42```
43
44## How it works
45
46React Router's type generation executes your route config (`app/routes.ts` by default) to determine the routes for your app.
47It then generates a `+types/<route file>.d.ts` for each route within a special `.react-router/types/` directory.
48With [`rootDirs` configured][route-module-type-safety], TypeScript can import these generated files as if they were right next to their corresponding route modules.
49
50For a deeper dive into some of the design decisions, check out our [type inference decision doc](https://github.com/remix-run/react-router/blob/main/decisions/0012-type-inference.md).
51
52[route-module-type-safety]: ../how-to/route-module-type-safety
53
54## `typegen` command
55
56You can manually generate types with the `typegen` command:
57
58```sh
59react-router typegen
60```
61
62The following types are generated for each route:
63
64- `LoaderArgs`
65- `ClientLoaderArgs`
66- `ActionArgs`
67- `ClientActionArgs`
68- `HydrateFallbackProps`
69- `ComponentProps` (for the `default` export)
70- `ErrorBoundaryProps`
71
72### --watch
73
74If you run `react-router dev` — or if your custom server calls `vite.createServer` — then React Router's Vite plugin is already generating up-to-date types for you.
75But if you really need to run type generation on its own, you can also use `--watch` to automatically regenerate types as files change:
76
77```sh
78react-router typegen --watch
79```