phantom-types
Arbitrarily narrow types
Inspiration
What is a phantom type?
A phantom type is a successful runtime assertion encoded as a static type.
A candidate value is checked against a predicate function at runtime and the static type checker is used to track that the check was successful. So we can safely validate at the edge of our programs only!
Some of the shipped types
CountryCode is special …
It’s implemented as a union of a Literal of all valid country codes, and a phantom type for parsing values not known at “compilation time”. This allows mixed statements like this to pass type checking:
Caveats and issues
Compatibility
Note that combining phantom types with runtime type checkers like beartype and typeguard is runtime-equivalent to “Design by contract”.
Extra: Some implementation details
Extra/discussion: Introducing phantom types
When introducing phantom types into an application like in the example, one should start at the ORM level. That will allow the type checker to reveal all places in the business logic layer that needs to be adapted.
After adapting the business logic layer, the type checker should reveal all places in the layer above that needs to be adapted.