In F#, the compiler is more than a hurdle before running an application. Its type errors can guide changes to a domain model: add a field to a record, and every place that constructs that record must supply it before the code compiles. Fixing those errors makes an incomplete update harder to overlook. section 1.5.3 section 2.1.4
This works best when types express the rules that matter. A train model can distinguish passenger and buffet carriages, record their features, and represent a possible driver change with an option. The compiler then checks code against those shapes as the model changes. section 2.1.4
When an error points away from the mistake
Suppose calculateGroup compares an age with 18. Replace 18 with "test", and F# may infer that age is a string. Errors then appear at comparisons and calls that pass integers. Check the inferred function type; a temporary int annotation on age can move the error to the mistaken comparison. section 3.2.4
type ValidatedEmail =
private | ValidatedEmail of string #1
member this.Value = match this with (ValidatedEmail e) -> e #2
static member Create (unvalidatedEmail:string) = #3
if unvalidatedEmail.Contains "@" then
Ok (ValidatedEmail unvalidatedEmail)
else
Error "Invalid email!"
let sendEmailSafe message (email:ValidatedEmail) = #4
...
...
...
Ok "Sent message"
let sendResult =
ValidatedEmail.Create "isaac@email.com"
|> Result.bind (sendEmailSafe "Welcome!") #5
A private ValidatedEmail case makes callers use Create before passing a value to sendEmailSafe. Validation remains logic to test, but the function's prerequisite is enforced by its parameter type. section 14.1.1
Compiler checks can reduce tests for structural mistakes and missing cases, including incomplete pattern matches on discriminated unions. They do not prove that every rule or behavior is correct: keep tests where logic, such as creating a validated value, still needs checking. section 14.1.1








