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