2.1.0 • Published 4 years ago

typesafe-joi v2.1.0

Weekly downloads
1,287
License
MIT
Repository
github
Last release
4 years ago

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
APIStatusNote
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)🔘
alternativesArray 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