Native Printer
TypeLang\Printer\NativeTypePrinter renders the closest type that PHP itself would accept. TypeLang can describe far more than the language can express — generics, shapes, conditional types, integer ranges — so the native printer trades that precision for validity, collapsing every construct without a native equivalent down to a supported approximation.
Use it to emit something the runtime can consume — a property type, a parameter or return hint, generated code — rather than something a human reads. For the latter, use the Pretty Printer.
It extends PrettyTypePrinter, so it accepts the same newLine and indention arguments; in practice they rarely show, because the constructs that would span several lines (shapes especially) are reduced to a single word first.
Conversion Rules
The printer keeps whatever PHP already understands and rewrites the rest:
TypeLang input | Native output | Rule |
|---|---|---|
|
| a shape becomes its base type |
|
| — |
|
| a callable loses its signature |
|
| a list suffix becomes |
|
| offset access is not expressible |
|
| class constants become |
|
| a literal becomes its type |
|
| — |
|
| a conditional becomes the union of its branches |
|
| the pair collapses to |
|
| any union containing |
Generic arguments are dropped along with everything else — array<int, User> prints as array, and class-string<Foo> as string.
Type Aliases
Much of the reduction is driven by a table of type aliases — a map from a type name to the native type it stands for. This is how positive-int becomes int and non-empty-list becomes array.
The printer preloads the built-in vocabularies of the three major static analyzers, so their custom scalar and collection types resolve out of the box:
Registering Your Own
Pass extra aliases as the first constructor argument, keyed by the alias name:
The same can be done after construction, which additionally allows an alias to a union or an intersection of several native types:
- addTypeAlias(string $alias, string $type)
Map an alias to a single native type.
- addUnionTypeAlias(string $alias, array $types)
Map an alias to a union of native types (joined with
|).- addIntersectionTypeAlias(string $alias, array $types)
Map an alias to an intersection of native types (joined with
&).
See Also
- Pretty Printer
Render the full, faithful type instead. See Pretty Printer.
- Type Printer
The component overview and the shared
print()contract. See Type Printer.