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
Methods that always throw aren't always recognized as a return from a function #39839
classLogger{throwError() : never{throwError();}}classFoo{logger: Logger;constructor(){this.logger=newLogger();}// does not compilefail(x : number) : number{if(x<0){returnx;}else{constlogger=newLogger();logger.throwError();}}// does compilesuccess1(x : number) : number{if(x<0){returnx;}else{this.logger.throwError();}}// does compilesuccess2(x: number,logger: Logger) : number{if(x<0){returnx;}else{logger.throwError();}}}
Expected behavior:
In all of these cases, the code should compile because logger.throwError() will always throw an error, therefore returning from the current function.
Actual behavior:
However, for the fail method, you get the compiler error
Function lacks ending return statement and return type does not include 'undefined'.(2366)
I'm not sure why the difference between having the logger as a field/parameter vs. a local variable causes some cases to compile but some not.
When we tried to start recognizing never-returning function calls, we tried to warn users that we couldn't recognize this the circularities that might occur in the control flow graph in #33622; however, we realized that it would break too much code using never-returning functions.
Daniel Rosenwasser (@DanielRosenwasser) Your explanation is right, but the whole issue is obviously pretty subtle. In #33622 it was possible for us to add errors when assertion functions are called in a manner than doesn't allow control flow analysis because assertion functions were a new feature, but we couldn't do it for never-returning functions because it broke existing code.
Activity
DanielRosenwasser commentedon Jul 30, 2020
I'm embarrassed because the workaround is so silly, but it will work if you annotate
logger.The issues are explained a bit on #34573.
When we tried to start recognizing
never-returning function calls, we tried to warn users that we couldn't recognize this the circularities that might occur in the control flow graph in #33622; however, we realized that it would break too much code usingnever-returning functions.Maybe Anders Hejlsberg (@ahejlsberg) can correct me if I got anything wrong.
ahejlsberg commentedon Jul 31, 2020
Daniel Rosenwasser (@DanielRosenwasser) Your explanation is right, but the whole issue is obviously pretty subtle. In #33622 it was possible for us to add errors when assertion functions are called in a manner than doesn't allow control flow analysis because assertion functions were a new feature, but we couldn't do it for
never-returning functions because it broke existing code.