Summary
The work that gcanti has done with io-ts is really useful, but it relies on a lot of language semantics that are exclusive to Typescript and the work on flow-io is now deprecated and no longer maintained. As a result, I have forked his work and refactored a lot of the existing combinators/classes so they more easily align with the semantics of Flow.
Table of Contents
- The idea
- Error handling
- Implemented types / combinators
- Flow compatibility
- Flow integration
- Mixing required and optional props
- Union Maps
- Refinements
- Custom types
- Tips and Tricks
The idea
Blog post: "Typescript and validations at runtime boundaries" by @lorefnon
Similiar to io-ts, a value of type Type<A, O, I>
(called "runtime type") is the runtime representation of the static type A
.
A runtime type can
- decode inputs of type
I
(throughdecode
) - encode outputs of type
O
(throughencode
) - be used as a custom type guard (through
is
)
type Validation<A> = Either<Errors A>; <A +O = A I = mixed> +_A: A +_O: O +_I: I {} /** a version of `validate` with a default context */ : Either<Errors A> /** a version of `validate` which will throw if invalid */ : A
Example
A runtime type representing string
can be defined as
// runtime type definitionType<string> // equivalent to Type<string, string, mixed> as per type parameter defaults { super 'string' m: m is typeof m === 'string' this ? t : t tidentity } // runtime type instance: use this when building other runtime types instancesconst string =
A runtime type can be used to validate an object in memory (for example an API payload)
const Person = t // validation succeededPerson // => right({name: "John", age: 43}) // validation failedPerson // => left([...]) //assertion succeededPerson // => {name: "John", age: 43} //assertion throwsPerson // => throws
Error handling
An error that is uncovered during decoding will be packed into an instance of the ValidationError
class.
+value: mixed; +context: Context; +message: string; }
Besides having a message
property, as is standard for Error classes in JavaScript, it also references the value which failed validation along with the context that was used in decoding. By default, if a message isn't supplied, a default one will be constructed based on the context reference
All errors that are uncovered during decoding will be packed into an instance of the AggregateErrors
class, which is a subclass of Array<ValidationError>
.
<ValidationError> messages(): Array<string>}
Errors can be still be extracted individually as elements of the wrapped array, and the messages can be extracted all at once via the introduction of the messages()
method on this class.
An example of Error inspection is shown below:
const Person = t // validation failed with decodeconst leftErr = Person // => left([...]) if leftErrtag === 'Left' const errs = leftErrvalue; console // => Invalid value undefined supplied to : { name: string, age: number }/name: string console // => Invalid value undefined supplied to : { name: string, age: number }/age: number try // validation throws with assert Person // => left([...]) catch errs console // => Invalid value undefined supplied to : { name: string, age: number }/name: string console // => Invalid value undefined supplied to : { name: string, age: number }/age: number
Error reporters
A reporter implements the following interface
interface Reporter<A> A
Example
const getPaths = <A>v: tValidation<A>: Array<string> return v const Person = ttype name: tstring age: tnumber console // => [ '.name', '.age' ]
Implemented types / combinators
Type | Flow | Runtime type / combinator |
---|---|---|
null | null |
t.Null |
undefined | undefined |
t.Undefined |
void | void |
t.Void |
string | string |
t.String |
number | number |
t.Number |
boolean | boolean |
t.Boolean |
any | any |
t.Any |
never | never |
t.Never |
object | object |
t.object |
integer | ✘ | t.Integer |
literal | 's' |
t.literal<'s'>('s') |
array of any | Array<mixed> |
t.arrayType |
array of type | Array<A> |
t.array(A) |
readonly array | $ReadOnlyArray<A> |
t.readonlyArray(A) |
dictionary of any | { [key: string]: mixed } |
t.Dictionary |
dictionary of type | { [key: A]: B } |
t.dictionary(A, B) |
tuple | [ A, B ] |
t.tuple([ A, B ]) |
union | A \| B |
t.union([ A, B ]) or t.unionMap({tagVal1: A, tagVal2: B}, tagName) |
intersection | A & B |
t.intersection([ A, B ]) |
keyof | keyof M |
t.keyof(M) |
refinement | A , Opaque: A |
t.refinement(A, predicate) ort.opaqueRefine<A, Opaque>(A, predicate) |
exact types | {\| a: A, b?: B \|} |
t.exact({required: {a :A}, optional: {b: B}}) |
{\| a: A, b: B \|} |
t.exactAll({a: A, b: B}) |
|
{\| a?: A, b?: B \|} |
t.exactShape({a: A, b: B} |
|
inexact types | { a: A, b: b } |
t.inexact({required: {a: A}, optional: {b: B}}) |
{ a: A, b: B } |
t.inexactAll({a: A, b: B}) |
|
{ a?: A, b?: B } |
t.inexactShape({a: A, b: B}) |
Note: Assume A
and B
are instances of the t.Type
class
Flow compatibility
The library is tested against a range of flow-bin
versions, which is listed as the peerDependencies
section of this NPM package.
Flow integration
Runtime types can be inspected
This library uses FLow extensively. Its API is defined in a way which automatically infers types for produced values
Static types can be extracted from runtime types using the TypeOf
operator
type IPerson = tTypeOf<typeof Person>; // same astype IPerson = name: string age: number; // also the same astype IPerson = $PropertyType<typeof Person '_A'>;
Mixing required and optional props
You can mix required and optional props using an intersection
const required = foo: tstring;const optional = bar: tnumber const C = texact<typeof required typeof optional>required optionaltype CT = tTypeOf<typeof C>; // same astype CT = foo: string bar?: number
You can call shape
to an already defined runtime type if created with one of the exact
or inexact
functions
const PersonType = t const PartialPersonType = Personshape; type PartialPerson = tTypeOf<typeof PartialPersonType>; // same astype PartialPerson = name?: string age?: number
Union Maps
If you are encoding tagged unions, instead of the general purpose union
combinator, you may want to use the
unionMap
combinator in order to get better performances
const A = t const B = t const U = t
Refinements
You can refine a type (any type) using the refinement
combinator
const Adult = t
However, unless you utilize Flow's opaque types, this can't be enforced via a static check. For stricter safety, you should use the opaqueRefine
function and supply the opaque type as a generic
opaque type Positive: number = number;const positive = topaqueRefine<typeof tNumber Positive>tNumber num > 0 'Positive'
Custom types
You can define your own types. Let's see an example
// represents a Date from an ISO stringconst DateFromString = <Date string> 'DateFromString' m: m is m instanceof Date tstring a const s = 1973 10 30 DateFromString// right(new Date('1973-11-29T23:00:00.000Z')) DateFromString// left(errors...)
Note that you can deserialize while validating.
Custom Error Messages
You can set your own error message by providing a message
argument to failure
Example
console.logPathReporter.reportNumberFromString.decode'a'// => ['cannot parse to a number']
Tips and Tricks
Is there a way to turn the checks off in production code?
No, however you can define your own logic for that (if you really trust the input)
; const NODE_ENV = processenv : t.Either<t.Errors, A> { if NODE_ENV !== 'production' || typeencode !== tidentity return type else // unsafe cast return t } // or... : A { if NODE_ENV !== 'production' || typeencode !== tidentity return type else // unsafe cast return value: any: A }
Union of string literals
Use keyof
instead of union
when defining a union of string literals
const Bad = t const Good = t
Benefits
- unique check for free
- better performance
- quick info stays responsive
Known issues
- TODO