-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Typescript not understand Promise than catch logic #25022
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
Comments
TypeScript doesn't have a way to correlate the types of Otherwise, being able to discriminate on |
That is bad because I need to hack data variable like this: |
I think @DanielRosenwasser might have looked at it a bit too quickly... What you have written int TypeScript could easily be improved to accomplish your intent: export interface ToReturn<T> {
error: Error | undefined;
data: T | undefined;
}
export default function to<T>(promise: Promise<T>): Promise<ToReturn<T>> {
return promise
.then((data: T) => {
return { error: undefined, data };
})
.catch((error: Error) => {
return { error, data: undefined };
});
}
async function someMethod() {
const { error, data } = await to(Promise.resolve('foo'));
if(error) {
return;
}
data; // typeof string
} These sort of basic questions are best asked on StackOverflow or Gitter though. |
Actually, @DanielRosenwasser is right, though I am not entirely sure you wanted/needed what Daniel was suggesting. While it is mildly inconvenient, you can still access the type. Your original code was still flawed though in representing the return of the function. Here is a slightly better example which expresses what Daniel was talking about when run under export type ToReturn<T> = {
error: Error;
data: undefined;
} | {
error: undefined;
data: T
};
export default function to<T>(promise: Promise<T>): Promise<ToReturn<T>> {
return promise
.then((data: T) => {
return { error: undefined, data };
})
.catch((error: Error) => {
return { error, data: undefined };
});
}
async function someMethod() {
const { error, data } = await to(Promise.resolve('foo'));
if (error) {
return;
}
data; // typeof string | undefined
if (data) {
data; // string
}
} |
Yes, in this part
data should be just string but not string | undefined |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
If I have promise like this:
And after that I add async await with this logic:
Maybe this is some bug with IDE I don't know. I am usigin Visual Code.
The text was updated successfully, but these errors were encountered: