Complex type validators that generate TypeScript or Flow types for you.
The validation errors are detailed. Adapted from the brilliant work in flow-runtime
.
- Introduction
- What about generating validators from type defs?
- API
- Type creators
t.any()
t.unknown()
t.boolean()
t.boolean(true)
t.string()
t.string('foo')
t.number()
t.number(3)
t.symbol()
t.symbol(MySymbol)
t.null()
/t.nullLiteral()
t.nullOr(t.string())
t.undefined()
/t.undefinedLiteral()
t.nullish()
t.nullishOr(t.string())
t.array(t.number())
t.object(properties)
t.object({ required?, optional?, exact? })
t.merge(...objectTypes)
t.mergeInexact(...objectTypes)
t.record(t.string(), t.number())
t.instanceOf(() => Date)
t.tuple(t.string(), t.number())
t.allOf(A, B)
t.oneOf(t.string(), t.number())
t.alias(name, type)
t.ref(() => typeAlias)
t.Type
accepts(input: any): boolean
acceptsSomeCompositeTypes: boolean (getter)
assert(input: any, prefix = '', path?: (string | number | symbol)[]): V
validate(input: any, prefix = '', path?: (string | number | symbol)[]): Validation
warn(input: any, prefix = '', path?: (string | number | symbol)[]): void
toString(): string
t.ExtractType>
t.TypeAlias
- Custom Constraints
- Recursive Types
- Type creators
When you need to validate the inputs to a TypeScript or Flow API, a problem arises. How do you ensure that a value that passes validation matches your declared TypeScript type? Someone might modify one and forget to modify the other:
type Post = {
author: {
name: string
username: string
}
content: string
// newly added by developer
tags: string[]
}
// hypothetical syntax
const validator = requireObject({
author: requireObject({
name: requireString(),
username: requireString(),
}),
content: requireString(),
// uhoh!! developer forgot to add tags here
})
typed-validators
solves this by generating TypeScript or Flow types from your validators:
import * as t from 'typed-validators'
const PostValidator = t.object({
author: t.object({
name: t.string(),
username: t.string(),
}),
content: t.string(),
tags: t.array(t.string()),
})
type Post = t.ExtractType<typeof PostValidator>
const example: Post = PostValidator.assert({
author: {
name: 'MC Hammer',
username: 'hammertime',
},
content: "Can't touch this",
tags: ['mc-hammer', 'hammertime'],
})
Hover over Post
in VSCode and you'll see, voilà:
type Post = {
author: {
name: string
username: string
}
content: string
tags: string[]
}
Example error message:
PostValidator.assert({
author: {
name: 'MC Hammer',
usernme: 'hammertime',
},
content: 1,
tags: ['mc-hammer', { tag: 'hammertime' }],
})
RuntimeTypeError: input.author is missing required property username, which must be a string
Actual Value: {
name: "MC Hammer",
usernme: "hammertime",
}
-------------------------------------------------
input.author has unknown property: usernme
Actual Value: {
name: "MC Hammer",
usernme: "hammertime",
}
-------------------------------------------------
input.content must be a string
Actual Value: 1
-------------------------------------------------
input.tags[1] must be a string
Actual Value: {
tag: "hammertime",
}
This is in the works at typed-validators-codemods
.
Once it's ready for prime time I'll publish it.
It creates or replaces validators anywhere you declare a variable of type t.TypeAlias
:
import * as t from 'typed-validators'
type Author = {
name: string
username: string
}
export type Post = {
author: Author
content: string
tags: string[]
}
export const PostType: t.TypeAlias<Post> = null
import * as t from 'typed-validators'
export type Author = {
name: string
username: string
}
const AuthorType: t.TypeAlias<Author> = t.alias(
'Author',
t.object({
name: t.string(),
username: t.string(),
})
)
export type Post = {
author: Author
content: string
tags: string[]
}
export const PostType: t.TypeAlias<Post> = t.alias(
'Post',
t.object({
author: t.ref(() => AuthorType),
content: t.string(),
tags: t.array(t.string()),
})
)
I recommend importing like this:
import * as t from 'typed-validators'
All of the following methods return an instance of t.Type<T>
.
A validator that accepts any value.
A validator that accepts any value but has TS unknown
type/Flow mixed
type.
A validator that requires the value to be a boolean
.
A validator that requires the value to be true
.
Note: to get the proper Flow types, you'll unforunately have to do t.boolean<true>(true)
.
A validator that requires the value to be a string
.
A validator that requires the value to be 'foo'
.
Note: to get the proper Flow types, you'll unfortunately have to do t.string<'foo'>('foo')
.
A validator that requires the value to be a number
.
A validator that requires the value to be 3
.
Note: to get the proper Flow types, you'll unfortunately have to do t.number<3>(3)
.
A validator that requires the value to be a symbol
.
A validator that requires the value to be MySymbol
.
A validator that requires the value to be null
.
A validator that requires the value to be string | null
A validator that requires the value to be undefined
.
A validator that requires the value to be null | undefined
.
A validator that requires the value to be string | null | undefined
.
A validator that requires the value to be number[]
.
A validator that requires the value to be number[]
.
Doesn't require the value to be frozen; just allows the extracted type to be ReadonlyArray
.
A validator that requires the value to be an object with all of the given required properties an no additional properties.
For example:
const PersonType = t.object({
name: t.string(),
age: t.number(),
})
PersonType.assert({ name: 'dude', age: 100 }) // ok
PersonType.assert({ name: 'dude' }) // error
PersonType.assert({ name: 1, age: 100 }) // error
PersonType.assert({ name: 'dude', age: 100, powerLevel: 9000 }) // error
A validator that requires the value to be an object with given properties.
Additional properties won't be allowed unless exact
is false
.
For example:
const PersonType = t.object({
required: {
name: t.string(),
},
optional: {
age: t.number(),
},
})
PersonType.assert({ name: 'dude' }) // ok
PersonType.assert({ name: 'dude', age: 100 }) // ok
PersonType.assert({ name: 1 }) // error
PersonType.assert({ name: 'dude', age: 'old' }) // error
Use t.readOnly(t.object(...))
or t.readOnly(t.merge(...))
etc. Doesn't require the object to be frozen, just allows the extracted type to be readonly.
Merges the properties of multiple object validators together into an exact object validator (no additional properties are allowed).
Note: merging t.alias
es and t.ref
s that resolve to object validators is supported, but any constraints on the referenced aliases won't be applied.
For example:
const PersonType = t.object({
required: {
name: t.string(),
},
optional: {
age: t.number(),
},
})
const AddressType = t.object({
street: t.string(),
city: t.string(),
state: t.string(),
zip: t.string(),
})
const PersonWithAddressType = t.merge(PersonType, AddressType)
PersonWithAddressType.assert({
// ok
name: 'dude',
age: 100,
street: 'Bourbon Street',
city: 'New Orleans',
zip: '77777',
})
Merges the properties of multiple object validators together into an inexact object validator (additional properties are allowed).
Note: merging t.alias
es and t.ref
s that resolve to object validators is supported, but any constraints on the referenced aliases won't be applied.
Accepts a variable number of arguments, though type generation is only overloaded up to 8 arguments. Accepts a variable number of arguments, though type generation is only overloaded up to 8 arguments.
A validator that requires the value to be Record<string, number>
.
A validator that requires the value to be an instance of Date
.
A validator that requires the value to be [string, number]
.
Accepts a variable number of arguments, though type generation for Flow is only overloaded up to 8 arguments.
A validator that requires the value to be A & B
. Accepts a variable number of arguments, though type generation is only overloaded up to 8 arguments. For example:
const ThingType = t.object({ name: t.string() })
const CommentedType = t.object({ comment: t.string() })
const CommentedThingType = t.allOf(ThingType, CommentedType)
CommentedThingType.assert({ name: 'foo', comment: 'sweet' })
A validator that requires the value to be string | number
. Accepts a variable number of arguments, though type generation is only overloaded up to 32 arguments.
Creates a TypeAlias
with the given name
and type
.
Type aliases serve two purposes:
- They allow you to create recursive type validators with
t.ref()
- You can add custom constraints to them
Creates a reference to the given TypeAlias
. See Recursive Types for examples.
The base class for all validator types.
T
is the type of values it accepts.
Returns true
if and only if input
is the correct type.
Returns true
if the validator accepts some values that are not primitives, null or undefined.
Throws an error if input
isn't the correct type.
prefix
will be prepended to thrown error messages.
path
will be prepended to validation error paths. If you are validating a function parameter named foo
,
pass ['foo']
for path
to get clear error messages.
Validates input
, returning any errors in the Validation
.
prefix
and path
are the same as in assert
.
Logs a warning to the console if input
isn't the correct type.
Returns a string representation of this type (using TS type syntax in most cases).
Gets the TypeScript type that a validator type accepts. For example:
import * as t from 'typed-validators'
const PostValidator = t.object({
author: t.object({
name: t.string(),
username: t.string(),
}),
content: t.string(),
tags: t.array(t.string()),
})
type Post = t.ExtractType<typeof PostValidator>
Hover over Post
in the IDE and you'll see, voilà:
type Post = {
author: {
name: string
username: string
}
content: string
tags: string[]
}
The name of the alias.
Adds custom constraints. TypeConstraint<T>
is a function (value: T) => string | null | undefined
which
returns nullish if value
is valid, or otherwise a string
describing why value
is invalid.
It's nice to be able to validate that something is a number
, but what if we want to make sure it's positive?
We can do this by creating a type alias for number
and adding a custom constraint to it:
const PositiveNumberType = t
.alias('PositiveNumber', t.number())
.addConstraint((value: number) => (value > 0 ? undefined : 'must be > 0'))
PositiveNumberType.assert(-1)
The assertion will throw a t.RuntimeTypeError
with the following message:
input must be > 0
Actual Value: -1
Creating validators for recursive types takes a bit of extra effort. Naively, we would want to do this:
const NodeType = t.object({
required: {
value: t.any(),
},
optional: {
left: NodeType,
right: NodeType,
},
})
But left: NodeTYpe
causes the error Block-scoped variable 'NodeType' referenced before its declaration
.
To work around this, we can create a TypeAlias
and a reference to it:
const NodeType: t.TypeAlias<{
value: any
left?: Node
right?: Node
}> = t.alias(
'Node',
t.object({
required: {
value: t.any(),
},
optional: {
left: t.ref(() => NodeType),
right: t.ref(() => NodeType),
},
})
)
type Node = t.ExtractType<typeof NodeType>
NodeType.assert({
value: 'foo',
left: {
value: 2,
right: {
value: 3,
},
},
right: {
value: 6,
},
})
Notice how we use a thunk function in t.ref(() => NodeType)
to avoid referencing NodeType
before its declaration.