Replies: 1 comment
-
|
I think something similar can be already done in userland by creating custom
Effect has the same issue, and community projects like I personally need to spend some time on this since the TypeScript stuff is a bit overwhelming for me 😅 For example, I don’t really get the difference between the |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Background
I’ve been rethinking error handling in TypeScript.
In TypeScript, throwing errors causes the error type to be
unknown. To refine it, we needinstanceofchecks or type guards, but we don’t get type safety for domain-specific error values.A common alternative is the Result pattern:
Libraries like Effect and neverthrow use this to provide type safety and better error modeling.
The Problem
To make this work with TanStack Query today, we need to do something like:
This allows
onErrorto catch errors, but we lose type information about what those errors are.If we instead return errors as part of the
queryFn:we preserve type safety, but the code becomes misleading (errors look like successes).
It also risks breaking built-in mechanisms like retries and suspense - because the call looks like a success but it failed internall.
What I’d Like
As a user, I want to express my code in terms of success and failure while retaining type safety for known errors.
I would like to introcude the distinction between a success API that returns error, and success API that returns success data and API failure. Maybe we can create a function that will tell tanstack query how to extract the error / data from the success data, and will pipe the data to
data,erroranddefect(current tanstack error)We can add a function like
extractSuccessValue<T, E>: (value: T | E) => T | nullthat can somehow split the success value that contains error to a differect value / callback.I'm not sure the current suggestion of my implementation is possible due to typescipt limitation, but I think we can somehow split between success values and errors with type-safety. Let me know what do you think
Beta Was this translation helpful? Give feedback.
All reactions