validation.ts
Validation for TypeScript
This module helps validating incoming JSON, url params, etc in a type safe manner.
validate
Every validator has a validate
function which returns a Result (either a {type: 'ok', value} or a {type: 'error', errors})
A validated value can be transformed at any point during the validation process (e.g. isoDate
).
Errors are accumulated.
if isOkresult else
In case of errors, The Result
contains an Array of { message: string, context: string }
where message
is a debug error message for developers and context
is the path where the error occured (e.g root / data / 0 / name
)
errorDebugString
will give you a complete debug string of all errors, e.g.
At [root / c] Error validating the key. "c" is not a key of {
"a": true,
"b": true
}
At [root / c] Error validating the value. Type error: expected number but got string
primitives
v.stringv.numberv.booleanv.nullv.undefinedv.isoDate
tagged primitive
Sometimes, a string
or a number
is not just any string or number but carries extra meaning, e.g: email
, uuid
, userId
, KiloGram
, etc.
Tagging such a primitive as it's being validated can help make the downstream code more robust.
literal
// The only value that can ever pass this validation is the 'X' string literal
array
tuple
object, literal union, optional
Note: For bigger unions of strings, consider using the keyof
validator instead.
dictionary
A dictionary is an object where all keys and all values share a common type.
keyof
keyValidator.validate'bb' // Ok<'aa' | 'bb' | 'cc'> = Ok('bb') // keyof typeof keys === typeof keyValidator.T === 'aa' | 'bb' | 'cc'
map, filter, flatMap
.filterstr.length > 3 .map`...` .flatMapOkstr.toLowerCase
recursion
Deriving the typescript type from the validator type
Note: this can be used with any combination of validators except ones using recursion
.
Instead of using the derived type as your sole interface, use it to compare its compatibility with your handcrafted interfaces which will always be more readable in IDE's tooltips.
Configuration
A Configuration object can be passed to modify the default behavior of the validators:
Configuration.transformObjectKeys
Transforms every keys of every objects before validating.
Thanks
To gcanti
and his io-ts
library which provided great inspiration.