Saturday, 15 February 2014

Forcing error in TypeScript compile with void return -



Forcing error in TypeScript compile with void return -

with next code:

function foo() : void { // } var f = foo(); // why no error here?

this not produce compiler warning/error though foo function has been declared not homecoming anything.

another case i'd prevent is:

if (foo()) { }

i'm building api used other developers, , typescript works encouraging type safety , helps grab mutual javascript errors otherwise caught in testing rather @ compile time. case though isn't apparently handled though in other languages c#. developers customers, , may not have much experience, want create platform robust possible, , grab many issues before code deployed.

is there reasonable way construction code prevent other code attempting utilize undefined result of function has no homecoming value? if foo doesn't homecoming anything, i'd rather code can phone call foo(); , not inadvertently expect valid homecoming value when doing assignment (or similar execution).

other programming languages grab type of code construction @ compile time (and display warning/error).

it because void valid typescript type declaration. e.g next valid

var f:void;

however not useful variable type.

from language spec (http://www.typescriptlang.org/content/typescript%20language%20specification.pdf):

note: might consider disallowing declaring variables of type void serve no useful purpose. however, because void permitted type argument generic type or function not feasible disallow void properties or parameters.

update: pointed out ryan : https://twitter.com/searyanc/status/479664200323579904 don't much additional typesafety if f:void disallowed. can't utilize f in meaningful way e.g. next compile errors.

var f:void; f.bar; // error function bar(f:{}){} bar(f); // error var baz:{a?:number} = f; // error // allowed cases f = undefined; f = null;

curious real world case though.

update based on question update: unfortunately don't see way compiler prevent this, since anything allowed in js/ts if statement. perhaps want boolean truthy/falsy restriction.

if (f()) { }

typescript

No comments:

Post a Comment