Typechecker: Introduction

The Hack typechecker is the primary tool that makes Hack such a unique language. Before run time, the typechecker analyzes all the code associated with your program for various typing errors, thus preventing nasty bugs that may only have been exposed at run time.

Without the typechecker, this simple example would fail at runtime.

<?php

namespace Hack\UserDocumentation\TypeChecker\Intro\Examples\RuntimeFail;

class A {
  public function foo() { return 2; }
}

function failing($x) {
  $a = new A();
  if ($x === 4) {
    $a = null;
  }
  // $a being null would only be caught at runtime
  // Fatal error: Uncaught exception 'BadMethodCallException' with message
  // 'Call to a member function foo() on a non-object (NULL)'
  $a->foo();
}

failing(4);
Output
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Call to a member function foo() on a non-object (null)' in /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/runtime-fail.php:17
Stack trace:
#0 /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/runtime-fail.php(20): Hack\UserDocumentation\TypeChecker\Intro\Examples\RuntimeFail\failing()
#1 {main}

However, when using the typechecker before you run your code, you can catch errors before deployment, saving users from nasty fatals that may occur.

<?hh

namespace Hack\UserDocumentation\TypeChecker\Intro\Examples\TypecheckerCatch;

class A {
  public function foo() { return 2; }
}

function failing($x) {
  $a = new A();
  if ($x === 4) {
    $a = null;
  }
  // $a being null would only be caught BEFORE runtime
  //   typechecker-catch.php:21:7,9: You are trying to access the member foo
  //                                 but this object can be null. (Typing[4064])
  //   typechecker-catch.php:12:10,13: This is what makes me believe it can be
  //                                   null
  //
  $a->foo();
}

failing(4);
Output
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Call to a member function foo() on a non-object (null)' in /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/typechecker-catch.php.type-errors:20
Stack trace:
#0 /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/typechecker-catch.php.type-errors(23): Hack\UserDocumentation\TypeChecker\Intro\Examples\TypecheckerCatch\failing()
#1 {main}

The typechecker statically analyzes your program, catching problems in all paths of your code. This is not compilation. It is super fast feedback on the various states that might occur in your program so you can handle them before your code is run. The typechecker literally monitors changes to your code and updates its analysis accordingly, in real time.

Combined with the power of type annotations, the typechecker is a powerful error-catching tool.