Added an optional generic type to API routes to enforce the return type #1956
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The returned type from an API route and the expected type from a fetcher have nothing to do and could change without warning.
Although this does not completely fix that, it does improve the type safety by adding an optional type enforcement.
Let me explain with an example:
Let's say you have a hook with the following fetcher:
You are expecting the route to return a response with the
CompletedRuns[]type.However, if the route logic changes at any point and you forget to update all hooks that use this route, you will not notice it!
Now, you can add this same type to the route, to enforce the return!
Tip
You can add the generic type in any
errorHandler,authHandleroradminHandler. You can even add it to all of them at the same time!Now that you have added the
CompletedRuns[]type to the handler, it will display a typecheck error if theresultobject does not match this defined type.So now, you can improve the dev exp by using the same type both on the route definition and useFetcher implementation!