You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Why doesn't awaiting a Promise<never> change reachability? #34955
(async()=>{letb: string;leta1=awaitPromise.reject();// returns Promise<never>b="";// Not unreachable?b.toUpperCase();// Not unreachable?})();
Expected behavior:
As a1 is inferred to be never (e.g. behaves like in the non-promised version), I expected the rest of the code to be marked as unreachable aswell:
functionreturnNever(): never{thrownewError();}(async()=>{letb: string;leta0=returnNever();// a0 is neverb="";// Unreachableb.toUpperCase();// Unreachable})();
Actual behavior:
The code after the never-returning promise is marked as reachable.
Related Question on StackOverflow: Has more code: https://stackoverflow.com/questions/58732814 Related Issue: #10973 (although marked as "Working as intended", it was changed later. 3.7.2 behaves like the issue opener expected).
If this is not a bug, what is the background for this behavior?
changed the title [-]Should awaiting a Promise<never> influence reachability?[/-][+]Why doesn't awaiting a Promise<never> influence reachability?[/+]on Nov 7, 2019
changed the title [-]Why doesn't awaiting a Promise<never> influence reachability?[/-][+]Why doesn't awaiting a Promise<never> change reachability?[/+]on Nov 7, 2019
Consider a logErrorAsync function that returns Promise<never>. It awaits something and then throws an error on every path (or goes into an infinite loop etc.). If the function does not return a Promise<never> but a never instead, it behaves as expected.
As of TS 3.7.3:
declarefunctionfetchB(): Promise<string>;asyncfunctionlogErrorAsync(err: any): Promise<never>{awaitfetch("/foo/...");console.log("Error has been submitted to analytics tool");thrownewError(err);}functionlogError(err: any): never{console.error(err);thrownewError(err);}(async()=>{letb: string;try{b=awaitfetchB();}catch(err){awaitlogErrorAsync(err);// awaiting Promise<never>}b.toUpperCase();// "Error: "b" is used before assignment;" would require workarounds})();//...(async()=>{letb: string;try{b=awaitfetchB();}catch(err){logError(err);// returns never}b.toUpperCase();// No error, as expected})();
Backlog = no immediate plans for us to work on it, but
Lack of "Help Wanted" = not really sure if there are major roadblocks to a solution. I think this would be a difficult first PR, but you are welcome to try.
asyncfunctionenterToExit(): Promise<never>{console.log("Press [Enter] to exit");forawait(consteventofkeypress()){if(event.key=="return"){break;}}Deno.exit();}
Reacted by Max Duval, Florian Schwalm and Andres Eloy Rivera Garcia
I believe the code is unreachable because Promise.reject() throws an error, not because the type is never. How would TypeScript know that the code is unreachable when it does not know that this method can throw an error?
In Java there is the throws keyword which defines what errors a method can throw, e.g
publicvoiderrors() throwsException {
thrownewException("Exception!");
}
publicvoidtest() {
this.errors(); // will error because `errors()` can throw `Exception` and you don't handle the error. Your options are to add `throws Exception` to the signature of `test` or handle the exception with try catch// unreachable code because possible error not handled
}
I believe this (much-needed IMO) feature has been requested in #13219 and until it's implemented we're stuck with unknown or any in catches and not having any checks for unhandled errors.
functionerrors(): never{thrownewError("Error!")}functiontest(){errors()console.log('this is unreachable, and typescript knows it')}
the throws syntax is a separate, unrelated issue about type inference in a catch clause, whereas this issue is a bug regarding reachability calculation by returning never for known, uncaught errors.
I have also run into this problem in the wild, specifically when using zod and a z.never() schema in an async workflow. the specific use case was implementing an ORM that handles PostgreSQL views in addition to standard tables.
the general approach i was taking looked like this...
classTable<TInsertextendsz.ZodSchema>{// ...asyncinsert(data: TInsert): Promise<TInsertextendsz.ZodNever : never : TInsert>{db.insert(insertSchema.parse(data))}}
and response will have the type of whatever the WebSocket is expected to respond with.
However, if it is known in advance that the WebSocket will never respond when foo() is called, then its type will be Promise<never>.
It would be useful if you could see that awaiting this call would result in unreachable code.
Does that leave you with never-to-be-fulfilled promises lying around? Or is it internally constructed so that there are no references to them and they can be garbage collected?
I'm also bumping upon this issue, but was able to work around it using return, which is not a clean solution. My language server was giving a 'could be undefined' type error in the calling scope after wrapping repetitive error reporting in an async call.
Original code
asyncfunctionparseFile(): Promise<File>{try{returnawaitsomething()}catch(cause){consterrMsg='went wrong'awaitdbLog(errMsg,{isError: true})console.error(errMsg,{ cause })thrownewError(errMsg,{ cause })// unreachable code}}
Async call with bug
asyncfunctionparseFile(): Promise<File|undefined>{try{returnawaitsomething()}catch(cause){awaitloggedCriticalError('went wrong',{ cause })// incorrectly assumed reachable code}}
Async call with bug workaround
asyncfunctionparseFile(): Promise<File>{try{returnawaitsomething()}catch(cause){// returning an awaited Promise<never> will not add void to the return type of parseFile()returnawaitloggedCriticalError('went wrong',{ cause })// unreachable code}}
The need for logging stuff immediately exists because enterprise code is touched by many hands and the error handling in the parent scope might accidentally toss the error message, while fixing that behaviour could introduce its own set of bugs in legacy code that depends on that behaviour. We all know there's no budget for fixing everything. 💸
The inferred return type changed from File to File | undefined and caused a type error right below it, but in other code it could have propagated into the scope of a colleague and they'd be adding a bunch of useless if/elses, adding complexity where it's not needed.
Activity
[-]Should awaiting a Promise<never> influence reachability?[/-][+]Why doesn't awaiting a Promise<never> influence reachability?[/+][-]Why doesn't awaiting a Promise<never> influence reachability?[/-][+]Why doesn't awaiting a Promise<never> change reachability?[/+]andrewbranch commentedon Dec 4, 2019
I think this makes sense, though two things are unclear to me:
Have you found real cases where you have a
Promise<never>? Would love to see some motivating examples.nikeee commentedon Dec 4, 2019
Consider a
logErrorAsyncfunction that returnsPromise<never>. It awaits something and then throws an error on every path (or goes into an infinite loop etc.). If the function does not return aPromise<never>but aneverinstead, it behaves as expected.As of TS 3.7.3:
andrewbranch commentedon Dec 6, 2019
Yeah, since we actually error on unreachable code, this does seem worthy of the bug label.
nicolas377 commentedon Jul 14, 2022
We're closing in on 2 years of this issue, is this something that the TS team wants to do themselves, or could I take this on as a first PR here?
andrewbranch commentedon Jul 14, 2022
Backlog = no immediate plans for us to work on it, but
Lack of "Help Wanted" = not really sure if there are major roadblocks to a solution. I think this would be a difficult first PR, but you are welcome to try.
RuinTD commentedon Dec 21, 2022
Also this:
https://github.com/FayneAldan/ArtemisWaypointMigrator/blob/a3f38352518ea5de1d9534dabb951bd8e7dda52c/migrate.ts#L15-L23
bradenhs commentedon Jan 11, 2023
Here's a real use case for this I ran into today: you want to flush your logs then exit the process e.g.
zefir-git commentedon Mar 4, 2023
I believe the code is unreachable because
Promise.reject()throws an error, not because the type isnever. How would TypeScript know that the code is unreachable when it does not know that this method can throw an error?In Java there is the
throwskeyword which defines what errors a method can throw, e.gI believe this (much-needed IMO) feature has been requested in #13219 and until it's implemented we're stuck with
unknownoranyin catches and not having any checks for unhandled errors.rintaun commentedon Jun 16, 2023
williamd5 this works properly without promises:
the
throwssyntax is a separate, unrelated issue about type inference in acatchclause, whereas this issue is a bug regarding reachability calculation by returningneverfor known, uncaught errors.I have also run into this problem in the wild, specifically when using
zodand az.never()schema in an async workflow. the specific use case was implementing an ORM that handles PostgreSQL views in addition to standard tables.the general approach i was taking looked like this...
jespertheend commentedon Oct 8, 2023
I have a
TypedMessengerwhich allows you to send messages to things like Workers or WebSockets.It works a bit like:
and
responsewill have the type of whatever the WebSocket is expected to respond with.However, if it is known in advance that the WebSocket will never respond when
foo()is called, then its type will bePromise<never>.It would be useful if you could see that
awaiting this call would result in unreachable code.darrylnoakes commentedon Oct 9, 2023
Does that leave you with never-to-be-fulfilled promises lying around? Or is it internally constructed so that there are no references to them and they can be garbage collected?
jespertheend commentedon Oct 9, 2023
I'm implementing the garbage collection using WeakRefs as we speak :)
jespertheend commentedon Oct 9, 2023
Actually, I just realised what I want to do isn't possible :/ So errors for unreachable code would actually be very convenient here.
toonvanvr commentedon Jun 28, 2024
I'm also bumping upon this issue, but was able to work around it using
return, which is not a clean solution. My language server was giving a 'could be undefined' type error in the calling scope after wrapping repetitive error reporting in an async call.The need for logging stuff immediately exists because enterprise code is touched by many hands and the error handling in the parent scope might accidentally toss the error message, while fixing that behaviour could introduce its own set of bugs in legacy code that depends on that behaviour. We all know there's no budget for fixing everything. 💸
The inferred return type changed from
FiletoFile | undefinedand caused a type error right below it, but in other code it could have propagated into the scope of a colleague and they'd be adding a bunch of useless if/elses, adding complexity where it's not needed.asynctype narrowing #62624 as a duplicate of this issuenikeee commentedon Jun 17, 2026
Found a new case involving definite return analysis and process.exit in Node.js:
That code should not error