3.1 Typedef

We briefly looked at typedefs while talking about anonymous structures and saw how we could shorten a complex structure type by giving it a name. This is precisely why typedefs are useful. Giving names to structure types might even be considered their primary function, and is so common that the distinction between the two appears somewhat blurry. Many Haxe users consider typedefs to actually be the structure.

A typedef can give a name to any other type:

typedef IA = Array<Int>;

This enables us to use IA in places where we would normally use Array<Int>. While this saves only a few keystrokes in this particular case, it can make a larger difference for more complex, compound types. Again, this is why typedef and structures seem so connected:

typedef User = {
  var age : Int;
  var name : String;
}

Typedefs are not textual replacements, but are actually real types. They can even have type parameters as the Iterable type from the Haxe Standard Library demonstrates:

typedef Iterable<T> = {
  function iterator() : Iterator<T>;
}