Skip to content

Instantly share code, notes, and snippets.

@esamattis
Created May 19, 2022 20:59
Show Gist options
  • Select an option

  • Save esamattis/d1172371b0efc1327b8617de6e044f64 to your computer and use it in GitHub Desktop.

Select an option

Save esamattis/d1172371b0efc1327b8617de6e044f64 to your computer and use it in GitHub Desktop.
TypeScript inference for Remix.run loaders and actions
import { json } from "@remix-run/node";
import { useActionData, useLoaderData } from "@remix-run/react";
export function useTypedLoaderData<T extends (arg: any) => any>(): Awaited<
ReturnType<T>
> {
return useLoaderData();
}
export function useTypedActionData<T extends (arg: any) => any>():
| Awaited<ReturnType<T>>
| undefined {
return useActionData();
}
export function typedJson<T>(data: T, init?: Parameters<typeof json>[1]): T {
return json(data, init) as any; // LIE, but practical 😎
}
@esamattis

Copy link
Copy Markdown
Author

@jonbilous

jonbilous commented Sep 9, 2022

Copy link
Copy Markdown

`import type { TypedResponse } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

type InferJSONData = T extends TypedResponse ? R : T;

type Fn = (...args: any[]) => any;

type InferLoaderData = InferJSONData<Awaited<ReturnType>>;

export const useTypedLoaderData = () => {
return useLoaderData<InferLoaderData>();
};`

took a pretty similar approach here, but instead am unwrapping the response type from the json() function, so the typedJson function isn't necessary.

@esamattis

Copy link
Copy Markdown
Author

@jonbilous This is not actually needed anymore since it is build into Remix

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