Skip to content

Instantly share code, notes, and snippets.

@esamattis
Created May 17, 2022 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esamattis/0af86e0b7ac0e70732f3fe748f69378c to your computer and use it in GitHub Desktop.
Save esamattis/0af86e0b7ac0e70732f3fe748f69378c to your computer and use it in GitHub Desktop.
Type inference for Remix loaders
import { DataFunctionArgs } from "@remix-run/node";
export async function loader({ request }: DataFunctionArgs) {
const user = getUser(request);
return typedJson({
email: user.email,
});
}
export default function Page() {
const user = useTypedLoaderData<typeof loader>();
return <div>Email: {user.email}</div>;
}
import { DataFunctionArgs, json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
// https://github.com/remix-run/remix/pull/1254#issuecomment-1126870942
export function useTypedLoaderData<T extends (arg: any) => any>(): Awaited<
ReturnType<T>
> {
return useLoaderData();
}
type Scalar = string | number | boolean | null | undefined;
export type JSON = Scalar | { [key: string]: JSON } | JSON[];
export function typedJson<T extends JSON>(
data: T,
init?: Parameters<typeof json>[1],
): T {
return json(data, init) as any; // LIE, but practical 😎
}
@esamattis
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment