Adding Constraints
TypeScript is extremely versatile for representing types like string
or number
, but what about email
or integer less than 100
?
In ArkType, conditions that narrow a type beyond its basis are called constraints.
Constraints are a first-class citizen of ArkType. They are fully composable with TypeScript's built-in operators and governed by the same underlying principles of set-theory.
Define
Let's create a new contact
Type that enforces our example constraints.
Compose
Imagine we want to define a new Type representing a non-empty list of Contact
.
While the expression syntax we've been using is ideal for creating new types, chaining is a great way to refine or transform existing ones.
Narrow
Structured constraints like divisors and ranges will only take us so far. Luckily, they integrate seamlessly with whatever custom validation logic you need.
We can invoke palindromicContact
anywhere to get validated data or a list of errors with a user-friendly summary.
You now know how to refine your types to enforce additional constraints at runtime.
But what if once your input is fully validated, you still need to make some adjustments before it's ready to use?
The final section of intro will cover morphs, an extremely powerful tool for composing and transforming Types.