Created
May 19, 2022 20:59
-
-
Save esamattis/d1172371b0efc1327b8617de6e044f64 to your computer and use it in GitHub Desktop.
TypeScript inference for Remix.run loaders and actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 😎 | |
} |
`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.
@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
Related https://twitter.com/esamatti/status/1527393894824042497