- Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
TypeScript compiler allows to define a function marked explicitly with a return type, with code branches which lead to an inconclusive return value!
I know It is valid in JavaScript function not to return a value on all code path, however in TypeScript being a javascript typed superset, I can imagine having a poor written function [without return value on all code path] could potentially break other codes and I'm talking null-references, type mismatch, NaN, ...
I believe when using TypeScript code in an explicitly typed expression, no-one needs all the ugly plumbings, input or type validation, undefined checking, ... One needs to be sure to write a code that couldn't break the way a dynamic language like javascript could!
The following is a valid JavaScript code and it could compile within TypeScript:
functionSomeMethod(){}When you explicitly mention that the method has a return value, the compiler throw an error:
functionSomeMethod(): number{}However it is not the case when the function does not return in all code path, and I don't understand if this is by design why bother preventing above code from compiling in the first place!
The followings are all wrong in a typed context yet the compiler ignores them as a valid code:
functionSomeMethod(): number{return;}functionSomeMethod(): number{returnnull;}functionSomeMethod(): number{if(false)return1;}functionSomeMethod(): number{try{return0;}catch(ex){}}