Replies: 2 comments 1 reply
-
You can use a script to generate a type with the list of route IDs, check https://sergiodxa.com/tutorials/strongly-type-remix-route-ids. |
Beta Was this translation helpful? Give feedback.
-
You can go one step further and get the type of the route's loader. What you want is a type like this: export type LoaderType<P> = P extends {loader: Function} ? P['loader'] : never
export type RouteLoaders = {
"root": LoaderType<typeof import("~/root")>;
"routes/_app": LoaderType<typeof import("~/routes/_app")>;
// etc
}; You can then define a wrapper for export function useTypedRouteLoaderData<ID extends keyof RouteLoaders>(
route: ID
) {
return useRouteLoaderData(route) as SerializeFrom<RouteLoaders[ID]>;
} If the route does not contain a loader then You can build a script to generate the import fs from "fs";
import path from "path";
import { readConfig } from "@remix-run/dev/dist/config";
(async () => {
const routes = (await readConfig(".")).routes;
const loaderType = Object.entries(routes)
.map(([, route]) => route.id)
.reduce(
(def, id) => `${def}\n "${id}": LoaderType<typeof import("~/${id}")>;`,
"export type RouteLoaders = {"
)
.concat("\n};");
const template = `export type LoaderType<P> = P extends {loader: Function} ? P['loader'] : never
${loaderType}
`;
fs.writeFileSync(path.join("app/generated/routeTypes.ts"), template, {
encoding: "utf-8",
flag: "w",
});
})(); This gives pretty nice type-safety. Of course, where it falls short is that what It would be interesting to see if it's possible to have a dynamic |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I just had a small refactor that moved/renamed some files and realized that a few useRouteLoaderData calls broke because the route ID was changed, but there were no errors anywhere at run time. Is there a way to make these route IDs type safe in the first place?
Beta Was this translation helpful? Give feedback.
All reactions