Chapter 4. Constraining Types
Many developers learn the basic type annotations and call it a day. But we’re far from done. There is a wealth of advanced type annotations that are invaluable. These advanced type annotations allow you to constrain types, further restricting what they can represent. Your goal is to make illegal states unrepresentable. Developers should physically not be able to create types that are contradictory or otherwise invalid in your system. You can’t have errors in your code if it’s impossible to create the error in the first place. You can use type annotations to achieve this very goal, saving time and money. In this chapter I’ll teach you six different techniques:
Optional-
Use to replace
Nonereferences in your codebase. Union-
Use to present a selection of types.
Literal-
Use to restrict developers to very specific values.
Annotated-
Use to provide additional description of your types.
NewType-
Use to restrict a type to a specific context.
Final-
Use to prevent variables from being rebound to a new value.
Let’s start with handling None references with Optional types.
Optional Type
Null references are often referred to as the “billion-dollar mistake,” coined by C.A.R. Hoare:
I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language. My goal was to ensure that all use of references should be absolutely ...