Type Annotations

Table of Contents

Type annotations allow for PHP code to be explicitly typed on parameters, class member variables and return values (types are inferred for locals). These annotated types are checked via a type checker. Here are examples of the same code without and with type annotations:

<?php
class MyClass {
  const 
MyConst 0;

  private 
$x;

  public function 
increment($x) {
    
$y $x 1;
    return 
$y;
  }
}
<?hh
class MyClass {
  const 
int MyConst 0;

  private 
string $x '';

  public function 
increment(int $x): int {
    
$y $x 1;
    return 
$y;
  }
}

It is clear that the second example provides more description and insight into the intention of the code. Type annotations provides three primary code improvements:

  • Readability by helping other developers understand the purpose and intention of the code. Many use comments to express such annotations. Hack formalizes such annotations.

  • Correctness by forbidding unsafe coding practices (e.g., sketchy null checks) as well as allowing tools to check type annotations before runtime.

  • Refactorability by allowing Hack to inherit the reliable and automatic refactoring of a statically typed language. It is quite difficult to refactor a dynamically typed language such as PHP. Renaming or changing the number of parameters to a function require a manual search of the code base to find all call sites. A type checker, however, will throw and display a list of errors when a "breaking" change is made that can then be fixed one-by-one (or automatically with tooling).

To Top