-
Notifications
You must be signed in to change notification settings - Fork 88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Better type inference when not chaining (better interop with async/await) #514
Comments
Looks awesome. Totally feel like this is something that is needed. |
I might be missing something but what does this achieve that .match() can’t ? |
This would be a selling point because it allows the seamless integration of async/await code. |
I had a problem with methods not correctly infering the value type on returned ResultAsync. In the following code, the type of
Even though I have fixed it with replacing
|
I second this. I have pretty much exactly the same code as @bvisch posted here in each project that uses neverthrow. Having them available from the package, well tested and with good type inference, would be wonderful. My version uses the import { Result, ResultAsync } from 'neverthrow'
export type AnyResult = Result<any, any>
export type InferResultError<T> =
T extends Result<infer _, infer E>
? E
: T extends ResultAsync<infer _, infer E>
? E
: never
export type InferResultValue<T> =
T extends Result<infer V, infer _>
? V
: T extends ResultAsync<infer V, infer _>
? V
: never
export function resultFromSafeAsyncFn<T extends AnyResult>(
fn: () => Promise<T>,
) {
return new ResultAsync(fn()) as ResultAsync<
InferResultValue<T>,
InferResultError<T>
>
} @bvisch have you considered this approach and found any downsides to it? |
This library is really helping us at work to make our code safer. However, we've noticed that readability can suffer when using .andThen/.orElse chains, especially when integrating with old async code that doesn't use neverthrow. On the other hand, if we don't chain functions, we get very unreadable return types.
Here's something we came up with to make migration easier (demo playground here):
And here's what they look like in use:
These functions would have saved us a lot of frustration if they were available to us from the start. Are there any issues with adding them to the library? I'm happy to do it if I can get sign-off. 🙂
The text was updated successfully, but these errors were encountered: