Typesafe Joi

A fork of joi that produces typed validation results in TypeScript
Alternatives To Typesafe Joi
Project NameStarsDownloadsRepos Using ThisPackages Using ThisMost Recent CommitTotal ReleasesLatest ReleaseOpen IssuesLicenseLanguage
Zod20,459855an hour ago244September 11, 2022175mitTypeScript
TypeScript-first schema validation with static type inference
Yup20,0168,9122,408a day ago115August 20, 2022168mitTypeScript
Dead simple Object schema validation
Ajv12,308801,6067,9855 days ago349March 22, 2022252mitTypeScript
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
Formily9,3341196 days ago209September 20, 202211mitTypeScript
📱🚀 🧩 Cross Device & High Performance Normal Form/Dynamic(JSON Schema) Form/Form Builder -- Support React/React Native/Vue 2/Vue 3
Type Graphql7,6942772863 days ago67October 06, 2021107mitTypeScript
Create GraphQL schema and resolvers with TypeScript, using classes and decorators!
Marshmallow6,4809,091969a day ago168June 26, 2022164mitPython
A lightweight library for converting complex objects to and from simple Python datatypes.
Superstruct6,417348296a month ago75September 22, 202275mitTypeScript
A simple and composable way to validate data in JavaScript (and TypeScript).
Jsonschema4,07515,5302,4242 days ago74July 07, 202232mitPython
An implementation of the JSON Schema specification for Python
Json Schema3,3448,5014893 months ago46April 13, 202296mitPHP
PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project
Kubeval3,04382021 days ago13April 26, 2021104otherGo
Validate your Kubernetes configuration files, supports multiple Kubernetes versions
Alternatives To Typesafe Joi
Select To Compare


Alternative Project Comparisons
Readme

typesafe-joi

typesafe-joi is a fork of @hapi/joi. More precisely, this is a fork of @types/hapi__joi because it has just redefined the essential APIs of joi. Almost all the APIs are the same as the original APIs, but limitations exists. That is why I create a new package.

typesafe-joi currently matches the API of @hapi/joi 15.x. And it requires TypeScript >=3.0.0 to work.

NOTE: typesafe-joi is still WIP. Sorry but I do not have enough time to write a unit test for it. Please feel free to open an issue when you find bugs or suggestions. I am glad to help!

What’s the difference?

The JavaScript APIs of typesafe-joi and joi are identical. However, its type definition lacks of the type information of the “value” behind the schema. That means, JavaScript knows what the validated object look like at runtime, but TypeScript does not know it at all at compile time. typesafe-joi records more information into schemas so that TypeScript is able to know what object you are validating at compile time.

Unfortunately not all joi APIs are able to be properly described in TypeScript. See Reference for more information.

Usage

Import and use joi from typesafe-joi:

import * as Joi from 'typesafe-joi'

The TypeScript magic is shown when you call .validate or .attempt:

const data: any = dataFromAnywhere

// { foo?: string } | undefined
Joi.object({ foo: Joi.string() }).validate(data).value

// { id: number, email?: string }[]
Joi.attempt(data, Joi.array()
  .items({
    id: Joi.number().integer().required(),
    email: Joi.string().email()
  })
  .required()
)

You can also use Literal to pull the data type out of the schema:

const schema = Joi.array()
  .items({
    id: Joi.number().integer().required(),
    email: Joi.string().email()
  })
  .required()

type T = Joi.Literal<typeof schema>

NOTE: I suggest to turn on strict option in the compiler options of TypeScript.

Typecasting

Not every API of typesafe-joi matches the original joi in types. typesafe-joi provides typecast helpers in case you have to define the resulting type manually.

// 'foo'
Joi.string().required() as Joi.Cast.String<'foo'>

If the typecast includes undefined type, the key will be optional.

// { foo?: Foo }
Joi.object({ foo: number().required() as Joi.Cast.Object<Foo | undefined> })

Typecasting means you have to define everything by yourself. Schema attributes like allow is discarded.

// number | 'foo' | true
Joi.number().allow('foo').default(true)

// 123
Joi.number().allow('foo').default(true) as Joi.Cast.Number<123>

TypeScript may complain about type mismatch. In this case assert the expression to any firstly.

// Error
Joi.object({
  foo: Joi.object().pattern(/\d+/, 1).allow(1) as Joi.Cast.Object<Foo>
})

// { map: Foo | 1 }
Joi.object({
  foo: Joi.object().pattern(/\d+/, 1).allow(1) as any as Joi.Cast.Object<Foo | 1>
})

I recommend not to use the schema anymore after typecast. The behavior will be undefined.

Supported schema types to cast:

  • Cast.Alternatives
  • Cast.Any
  • Cast.Array
  • Cast.Binary
  • Cast.Boolean
  • Cast.Date
  • Cast.Function
  • Cast.Lazy
  • Cast.Number
  • Cast.Object
  • Cast.String

Reference

Here is a list of APIs of joi.

  • ✅ - Fully supported
  • ✔️ - Supported but might be incorrect (not well tested)
  • ⚠️ - Partially supported (with limitations)
  • ❌ - Not supported (however you can use it without auto type generation)
  • 🔘 - Supported but no type generation needed
API Status Note
Joi
version 🔘
validate(value, schema, [options], [callback])
compile(schema) ✔️
describe(schema) 🔘
assert(value, schema, [message])
attempt(value, schema, [message])
ref(key, [options]) 🔘
isRef(ref) 🔘
reach(schema, path)
defaults(fn) 🔘
bind() 🔘
extend(extension) 🔘 Requires module augmentation to typesafe-joi
any
any.validate(value, [options], [callback])
any.allow(value)
any.valid(value)
any.invalid(value)
any.required()
any.optional()
any.forbidden()
any.strip() ⚠️ The object key will still exist. It will have never type.
any.description(desc) 🔘
any.notes(notes) 🔘
any.tags(tags) 🔘
any.meta(meta) 🔘
any.example(...values) 🔘
any.unit(name) 🔘
any.options(options) 🔘 To properly use typesafe-joi, do not change convert, presence, noDefaults.
any.strict(isStrict) 🔘
any.default(value, [description]) ⚠️ Manually define the default type when using reference as default.
any.concat(schema) ✔️
any.when(condition, options) ✔️
any.label(name) 🔘
any.raw(isRaw) 🔘
any.empty(schema)
any.error(err, [options]) 🔘
any.describe() 🔘
array
array.sparse([enabled])
array.single([enabled]) 🔘
array.items(type)
array.ordered(type) ⚠️ No actual item order in the resulting type
array.min(limit) 🔘
array.max(limit) 🔘
array.length(limit) 🔘
array.unique([comparator], [options]) 🔘
array.has(schema) 🔘
boolean
boolean.truthy(value) 🔘
boolean.falsy(value) 🔘
boolean.insensitive([enabled]) 🔘
binary
binary.encoding(encoding) 🔘
binary.min(limit) 🔘
binary.max(limit) 🔘
binary.length(limit) 🔘
date
date.min(date) 🔘
date.max(date) 🔘
date.greater(date) 🔘
date.less(date) 🔘
date.iso() 🔘
date.timestamp([type]) 🔘
func
func.arity(n) 🔘
func.minArity(n) 🔘
func.maxArity(n) 🔘
func.class() 🔘
func.ref() 🔘
number
number.unsafe([enabled]) 🔘
number.min(limit) 🔘
number.max(limit) 🔘
number.greater(limit) 🔘
number.less(limit) 🔘
number.integer() 🔘
number.precision(limit) 🔘
number.multiple(base) 🔘
number.positive() 🔘
number.negative() 🔘
number.port() 🔘
object
object.keys([schema])
object.append([schema])
object.min(limit)
object.max(limit)
object.length(limit)
object.pattern(pattern, schema) ⚠️ The result type of pattern may be useless.
object.and(peers)
object.nand(peers)
object.or(peers)
object.xor(peers)
object.oxor(...peers)
object.with(key, peers)
object.without(key, peers)
object.rename(from, to, [options])
object.assert(ref, schema, [message]) 🔘
object.unknown([allow]) 🔘
object.type(constructor, [name]) ⚠️ If you need to combine keys and type, make sure type is the last call (.keys(...).type(...)), or the resulting type will be incorrect.
object.schema() ⚠️ Same as type.
object.requiredKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
object.optionalKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
object.forbiddenKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
string
string.insensitive() 🔘
string.min(limit, [encoding]) 🔘
string.max(limit, [encoding]) 🔘
string.truncate([enabled]) 🔘
string.creditCard() 🔘
string.length(limit, [encoding]) 🔘
string.regex(pattern, [options]) 🔘
string.replace(pattern, replacement) 🔘
string.alphanum() 🔘
string.token() 🔘
string.email([options]) 🔘
string.ip([options]) 🔘
string.uri([options]) 🔘
string.guid() - aliases: uuid 🔘
string.hex([options]) 🔘
string.base64([options]) 🔘
string.dataUri([options]) 🔘
string.hostname() 🔘
string.normalize([form]) 🔘
string.lowercase() 🔘
string.uppercase() 🔘
string.trim([enabled]) 🔘
string.isoDate() 🔘
symbol
symbol.map(map) 🔘
alternatives Array literal alternatives schema is not supported yet.
alternatives.try(schemas)
alternatives.when(condition, options) ✔️
lazy

Contribution

Feel free to submit an issue or PR if you have any ideas, or found any bugs.

License

MIT

Popular Validation Projects
Popular Schema Projects
Popular Data Processing Categories
Related Searches

Get A Weekly Email With Trending Projects For These Categories
No Spam. Unsubscribe easily at any time.
Typescript
Types
Validation
Schema
Hapi
Typesafe