Gathering detailed insights and metrics for typed-validators
Gathering detailed insights and metrics for typed-validators
Gathering detailed insights and metrics for typed-validators
Gathering detailed insights and metrics for typed-validators
gen-typed-validators
convert type annotations to typed-validators
sequelize-validate-subfields-typed-validators
sequelize-validate-subfields adapter for typed-validators
jlf-typed-form-craft
A library to create forms with typed datas and validations
extractor-of-type
Generate typed JavaScript runtime validators from Flow type declarations
complex type validators that generate TypeScript and Flow types for you
npm install typed-validators
Typescript
Module System
Node Version
NPM Version
TypeScript (99.47%)
JavaScript (0.53%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
8 Stars
74 Commits
2 Forks
2 Watchers
2 Branches
2 Contributors
Updated on Dec 18, 2024
Latest Version
4.5.1
Package Id
typed-validators@4.5.1
Unpacked Size
635.85 kB
Size
109.89 kB
File Count
251
NPM Version
8.1.2
Node Version
16.13.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
43
Complex type validators that generate TypeScript or Flow types for you.
The validation errors are detailed. Adapted from the brilliant work in flow-runtime
.
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.readonlyArray(t.number())
t.object(properties)
t.object({ required?, optional?, exact? })
t.opaque<DateString>(() => t.string())
t.readonly(objectType)
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<T>
accepts(input: any): boolean
acceptsSomeCompositeTypes: boolean (getter)
assert<V extends T>(input: any, prefix = '', path?: (string | number | symbol)[]): V
validate(input: any, prefix = '', path?: (string | number | symbol)[]): Validation<T>
warn(input: any, prefix = '', path?: (string | number | symbol)[]): void
toString(): string
t.ExtractType<T extends Type<any>>
t.TypeAlias<T>
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:
1type Post = { 2 author: { 3 name: string 4 username: string 5 } 6 content: string 7 // newly added by developer 8 tags: string[] 9} 10 11// hypothetical syntax 12const validator = requireObject({ 13 author: requireObject({ 14 name: requireString(), 15 username: requireString(), 16 }), 17 content: requireString(), 18 // uhoh!! developer forgot to add tags here 19})
typed-validators
solves this by generating TypeScript or Flow types from your validators:
1import * as t from 'typed-validators' 2 3const PostValidator = t.object({ 4 author: t.object({ 5 name: t.string(), 6 username: t.string(), 7 }), 8 content: t.string(), 9 tags: t.array(t.string()), 10}) 11 12type Post = t.ExtractType<typeof PostValidator> 13 14const example: Post = PostValidator.assert({ 15 author: { 16 name: 'MC Hammer', 17 username: 'hammertime', 18 }, 19 content: "Can't touch this", 20 tags: ['mc-hammer', 'hammertime'], 21})
Hover over Post
in VSCode and you'll see, voilà:
1type Post = { 2 author: { 3 name: string 4 username: string 5 } 6 content: string 7 tags: string[] 8}
Example error message:
1PostValidator.assert({ 2 author: { 3 name: 'MC Hammer', 4 usernme: 'hammertime', 5 }, 6 content: 1, 7 tags: ['mc-hammer', { tag: 'hammertime' }], 8})
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",
}
t.ExtractType<...>
for deeply nested object types. Past a certain level of complexity
it seems to give up and use any
for some object-valued properties. That's why I created gen-typed-validators
,
so that you can control the type definitions and generate typed-validators
from them.t.instanceOf(() => Function)
, but Flow treats the Function
type as any
. I may add t.function()
in the future, but
it won't validate argument or return types, because those can't be determined from function instances at runtime.babel-plugin-flow-runtime
basically tried to do, and it was too ambitious. I created this so that I could
stop using it.)This is now possible with gen-typed-validators
!
It creates or replaces validators anywhere you declare a variable of type t.TypeAlias
:
1// Post.ts 2import * as t from 'typed-validators' 3 4type Author = { 5 name: string 6 username: string 7} 8 9export type Post = { 10 author: Author 11 content: string 12 tags: string[] 13} 14 15export const PostType: t.TypeAlias<Post> = null
1$ gen-typed-validators Post.ts
1// Post.ts 2import * as t from 'typed-validators' 3 4export type Author = { 5 name: string 6 username: string 7} 8 9const AuthorType: t.TypeAlias<Author> = t.alias( 10 'Author', 11 t.object({ 12 name: t.string(), 13 username: t.string(), 14 }) 15) 16 17export type Post = { 18 author: Author 19 content: string 20 tags: string[] 21} 22 23export const PostType: t.TypeAlias<Post> = t.alias( 24 'Post', 25 t.object({ 26 author: t.ref(() => AuthorType), 27 content: t.string(), 28 tags: t.array(t.string()), 29 }) 30)
I recommend importing like this:
1import * as t from 'typed-validators'
All of the following methods return an instance of t.Type<T>
.
t.any()
A validator that accepts any value.
t.unknown()
A validator that accepts any value but has TS unknown
type/Flow mixed
type.
t.boolean()
A validator that requires the value to be a boolean
.
t.boolean(true)
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)
.
t.string()
A validator that requires the value to be a string
.
t.string('foo')
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')
.
t.number()
A validator that requires the value to be a number
.
t.number(3)
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)
.
t.symbol()
A validator that requires the value to be a symbol
.
t.symbol(MySymbol)
A validator that requires the value to be MySymbol
.
t.null()
/ t.nullLiteral()
A validator that requires the value to be null
.
t.nullOr(t.string())
A validator that requires the value to be string | null
t.undefined()
/ t.undefinedLiteral()
A validator that requires the value to be undefined
.
t.nullish()
A validator that requires the value to be null | undefined
.
t.nullishOr(t.string())
A validator that requires the value to be string | null | undefined
.
t.array(t.number())
A validator that requires the value to be number[]
.
t.readonlyArray(t.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
.
t.object(properties)
A validator that requires the value to be an object with all of the given required properties an no additional properties.
For example:
1const PersonType = t.object({ 2 name: t.string(), 3 age: t.number(), 4}) 5 6PersonType.assert({ name: 'dude', age: 100 }) // ok 7PersonType.assert({ name: 'dude' }) // error 8PersonType.assert({ name: 1, age: 100 }) // error 9PersonType.assert({ name: 'dude', age: 100, powerLevel: 9000 }) // error
t.object({ required?, optional?, exact? })
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:
1const PersonType = t.object({ 2 required: { 3 name: t.string(), 4 }, 5 optional: { 6 age: t.number(), 7 }, 8}) 9 10PersonType.assert({ name: 'dude' }) // ok 11PersonType.assert({ name: 'dude', age: 100 }) // ok 12PersonType.assert({ name: 1 }) // error 13PersonType.assert({ name: 'dude', age: 'old' }) // error
t.opaque<DateString>(() => t.string())
A validator that requires the value to be a string, but presents the type as DateString
(for instance with export opaque type DateString = string
)
t.readonly(objectType)
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.
t.merge(...objectTypes)
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:
1const PersonType = t.object({ 2 required: { 3 name: t.string(), 4 }, 5 optional: { 6 age: t.number(), 7 }, 8}) 9const AddressType = t.object({ 10 street: t.string(), 11 city: t.string(), 12 state: t.string(), 13 zip: t.string(), 14}) 15 16const PersonWithAddressType = t.merge(PersonType, AddressType) 17 18PersonWithAddressType.assert({ 19 // ok 20 name: 'dude', 21 age: 100, 22 street: 'Bourbon Street', 23 city: 'New Orleans', 24 zip: '77777', 25})
t.mergeInexact(...objectTypes)
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.
t.record(t.string(), t.number())
A validator that requires the value to be Record<string, number>
.
t.instanceOf(() => Date)
A validator that requires the value to be an instance of Date
.
t.tuple(t.string(), t.number())
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.
t.allOf(A, B)
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:
1const ThingType = t.object({ name: t.string() }) 2const CommentedType = t.object({ comment: t.string() }) 3 4const CommentedThingType = t.allOf(ThingType, CommentedType) 5 6CommentedThingType.assert({ name: 'foo', comment: 'sweet' })
t.oneOf(t.string(), t.number())
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.
t.alias(name, type)
Creates a TypeAlias
with the given name
and type
.
Type aliases serve two purposes:
t.ref()
t.ref(() => typeAlias)
Creates a reference to the given TypeAlias
. See Recursive Types for examples.
t.Type<T>
The base class for all validator types.
T
is the type of values it accepts.
accepts(input: any): boolean
Returns true
if and only if input
is the correct type.
acceptsSomeCompositeTypes: boolean (getter)
Returns true
if the validator accepts some values that are not primitives, null or undefined.
assert<V extends T>(input: any, prefix = '', path?: (string | number | symbol)[]): V
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.
validate(input: any, prefix = '', path?: (string | number | symbol)[]): Validation<T>
Validates input
, returning any errors in the Validation
.
prefix
and path
are the same as in assert
.
warn(input: any, prefix = '', path?: (string | number | symbol)[]): void
Logs a warning to the console if input
isn't the correct type.
toString(): string
Returns a string representation of this type (using TS type syntax in most cases).
t.ExtractType<T extends Type<any>>
Gets the TypeScript type that a validator type accepts. For example:
1import * as t from 'typed-validators' 2 3const PostValidator = t.object({ 4 author: t.object({ 5 name: t.string(), 6 username: t.string(), 7 }), 8 content: t.string(), 9 tags: t.array(t.string()), 10}) 11 12type Post = t.ExtractType<typeof PostValidator>
Hover over Post
in the IDE and you'll see, voilà:
1type Post = { 2 author: { 3 name: string 4 username: string 5 } 6 content: string 7 tags: string[] 8}
t.TypeAlias<T>
readonly name: string
The name of the alias.
addConstraint(...constraints: TypeConstraint<T>[]): this
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:
1const PositiveNumberType = t 2 .alias('PositiveNumber', t.number()) 3 .addConstraint((value: number) => (value > 0 ? undefined : 'must be > 0')) 4 5PositiveNumberType.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:
1const NodeType = t.object({ 2 required: { 3 value: t.any(), 4 }, 5 optional: { 6 left: NodeType, 7 right: NodeType, 8 }, 9})
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:
1const NodeType: t.TypeAlias<{ 2 value: any 3 left?: Node 4 right?: Node 5}> = t.alias( 6 'Node', 7 t.object({ 8 required: { 9 value: t.any(), 10 }, 11 optional: { 12 left: t.ref(() => NodeType), 13 right: t.ref(() => NodeType), 14 }, 15 }) 16) 17 18type Node = t.ExtractType<typeof NodeType> 19 20NodeType.assert({ 21 value: 'foo', 22 left: { 23 value: 2, 24 right: { 25 value: 3, 26 }, 27 }, 28 right: { 29 value: 6, 30 }, 31})
Notice how we use a thunk function in t.ref(() => NodeType)
to avoid referencing NodeType
before its declaration.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 1/29 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
25 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More