Can types replace validation?

I'm playing with an idea of validating values using types in a functional language. I didn't think of how to represent it in existing languages like C# or TypeScript. But from the language design perspective it's possible.

Even type checker can be Turing complete if we implement it as an expression evaluator but it can go into an infinite loop during compile type. The solution for this in my perspective is to decide whenever we can validate the value based on type during compile time or not. If not, we can just move the validation into runtime. Also, we can setup a limit for an evaluator and just say - ok, we weren't able to determine the validity during n steps, just forget it and let the runtime deal with it.

As you mentioned, validation is not about simple true/false but we need to carry the validation error somehow. This can be solved by having types as first-class citizen that can be accessed also as a value. Basically, having a validating types we need to assign them some attributes - like Integer<min=0,max=255> and we can use another type to hold the error, like Error<message="Value is out of range.">. In functional languages, errors are often passed as other types.

So in pseudocode you can have something like:

type Email = String<pattern=/some_regexp/>
class Person {
Uid id;
Email email;
String<minLength=1> firstName;
String<minLength=1> lastName;
}
const goodJohn = Person {
id: genUid(),
email: "[email protected]",
firstName: "John",
lastName: "Doe"
}
const badJohn = Person {
id: genUid(),
email: "[email protected]",
firstName: "John",
lastName: ""
}
// typeof goodJohn = Person
// typeof badJohn = ValidationError<message="Property 'lastName' is not valid: Value does not match minLength constraint of '1'">

This approach of course requires a language with union types.

/r/programming Thread Link - blog.ploeh.dk