refactor(react-router): never
return type for notFound
#2248
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.
Currently, when you call
notFound({ throw: true })
Typescript does not identify it as never returning.A discussion of this issue: #2168
Here is an example:
Typescript infers the return type of the
loader
function in this case to be either a data structure orundefined
ornull
. Since the type being returned is a subset of another object, defining an explicit type is not very efficient.Fortunately Typescript can be given a hint that the
notFound
function will never return, and in that case will infer a non-nullable return type.Because the
notFound
function only raises an exception when thethrows
option is true, this is expressed as an overload of the function. The overloads tell Typescript the concrete return types depending on options passed, returningnever
whenthrows
is true, and returning aNotFoundError
in other cases.With this in place, the result of
Route.useLoaderData()
is a non-nullable data structure.(The
throws: true
implementation is desired when using eslint, since it will complain about throwing aNotFoundError
because it does not inherit fromError
. By asking the function to throw instead, we can bypass the eslint complaint. The complaint is otherwise desirable, but the internal implementation of the router throws and catches these specificNotFoundError
objects, and our application should not catch one, so the eslint complaint is not applicable.)