In an untyped language, runtime assertions can catch "type errors":
<?php
function add_one($x) {
assert(is_int($x));
return $x+1;
}
?>
With Hack's type annotations, I would want to delete the assertions, but this is unsafe because untyped code may still call typed functions.
<?hh // strict
function add_one(int $x): int {
return $x+1;
}
function evil(): void {
// UNSAFE
add_one("yes"); // Runtime error!
}
?>
To any professional Hack developers: do you enforce type signatures with assertions? (I'd really like to know what Facebook's policy is, but I understand if that's a secret.)
Failing to meet a type signature at run time throws an E_RECOVERABLE_ERROR
. How you handle this is up to your error handler.
Using assert
is advised against as it's a configuration-controlled version of eval
. Instead, Hack introduces the invariant
function, which you can use to provide information to the type checker which you know to be true but it can't figure out. Calls to invariant
are always checked at runtime and will throw an exception if they fail.
So, in your example, I wouldn't have any additional checks as the add_one("yes");
call will already result in an error at runtime.