Function return value constraints · Issue #228 · microsoft/TypeScript (original) (raw)

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:

function SomeMethod() { }

When you explicitly mention that the method has a return value, the compiler throw an error:

function SomeMethod(): 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:

function SomeMethod(): number { return; }

function SomeMethod(): number { return null; }

function SomeMethod(): number { if (false) return 1; }

function SomeMethod(): number { try { return 0; } catch (ex) { } }