The idea
A value of type Type<T>
(called "runtime type") is a representation of the type T
:
<T> name: string; Validation<T>;
where Context
and Validation<T>
are defined as
type ContextEntry = key: string name: string ;type Context = Array<ContextEntry>;type ValidationError = value: mixed context: Context description: string ;type Validation<T> = Either<Array<ValidationError> T>;
Example: a runtime type representing the type string
is
const string: Type<string> = 'string' typeof v === 'string' ? t : t
A runtime type can be used to validate an object in memory (for example an API payload)
const Person = tobject name: tstring age: tnumber // okt // => {name: "Giulio", age: 43} // throws Invalid value undefined supplied to : { name: string, age: number }/age: numbert // doesn't throw, returns an Eitherconst validation = tt
Runtime type introspection
Runtime types can be inspected
const Name: Type<string> = Personpropsnameconst Age: Type<number> = Personpropsage
Error reporters
A reporter implements the following interface
This package exports two default reporters
PathReporter: Reporter<Array<string>>
ThrowReporter: Reporter<void>
Example
const validation = tconsole // => ["Invalid value "a" supplied to : number"]ThrowReporter // => throws Invalid value "a" supplied to : number
Implemented types / combinators
Type | Flow syntax | Runtime type / combinator |
---|---|---|
string | string |
string |
number | number |
number |
boolean | boolean |
boolean |
generic object | Object |
Object |
generic function | Function |
Function |
instance of C |
C |
instanceOf(C) |
class of C |
Class<C> |
classOf(C) |
array | Array<A> |
array(A) |
intersection | A & B |
intersection([A, B]) |
literal | 's' |
literal('s') |
maybe | ?A |
maybe(A) |
map | { [key: A]: B } |
mapping(A, B) |
refinement | ✘ | refinement(A, predicate) |
object | { name: string } |
object({ name: string }) |
tuple | [A, B] |
tuple([A, B]) |
union | A | B |
union([A, B]) |
$Exact | {| name: string |} |
$exact({ name: string }) |
function | (a: A) => B |
✘ |