Enhancing LoaderFunction
with TS generics
#2201
Replies: 4 comments 3 replies
-
There's a somewhat similar discussion here Ryan explains why it's kind of a bad idea here That being said, there is a library that does what you want There's also the more mature And a corresponding discussion to have that one baked into Remix And finally, a closed PR that should give you an idea on what to do to achieve that |
Beta Was this translation helpful? Give feedback.
-
In addition to the response from @hollandThomas, you should not wrap your loader function in a HOC. The reason is that your loader will now be included in your client bundle. Your |
Beta Was this translation helpful? Give feedback.
-
Thanks everyone. This sounds very similar to why Firestore doesn't use generics - ie, you don't actually know what's coming across the wire and it should be considered untrusted by client code. |
Beta Was this translation helpful? Give feedback.
-
Agreed it will make a lot more sense when type-fest could be helpful for constraining what AppData is. They/we are working on a Jsonifiable type where something is export type AppData = Jsonifiable
export function useLoaderData<T extends AppData>(): T {
return useRemixRouteContext().data;
}
const getData = ()=> { ... }
export const loader = ()=>return new Response(...)
export default Index:FC = ()=>{
const myData = useLoaderData<ReturnType<typeof getData>>() // This would produce a type error if getData()'s return type was not Jsonifiable
} |
Beta Was this translation helpful? Give feedback.
-
Hello, I have a suggestion for genericizing
LoaderFunction
and adding helper factory for improved Typescript support.First, a generic
LoaderFunction
type:This would be backward compatible but would also mean that the function return type can be picked up by Typescript.
Next, I created a factory helper that accepts a loader function and returns the typed loader and a typed
useLoaderData
:I like this approach because then I don't need to create any custom types. It can all be inferred from the loader function return type.
Thoughts?
Beta Was this translation helpful? Give feedback.
All reactions