Library update: ajv-ts 0.5
Installation/Update
npm i ajv-ts@latest # npm
yarn add ajv-ts@latest # yarn
pnpm add ajv-ts@latest # pnpm
bun add ajv-ts@latest # bun
New Features
not, exclude
Now you can mark your schema with not
keyword!
Here is a 2 differences between not
and exclude
.
not
method wrap given schema withnot
exclude(schema)
- addnot
keyword for incomingschema
argument
Example:
import s from 'ajv-ts';
// not
const notAString = s.string().not(); // or s.not(s.string())
notAString.valid('random string'); // false, this is a string
notAString.valid(123); // true
// exclude
const notJohn = s.string().exclude(s.const('John'));
notJohn.valid('random string'); // true
notJohn.valid('John'); // false, this is John
// advanced usage
const str = s.string<'John' | 'Mary'>().exclude(s.const('John'))
s.infer<typeof str> // 'Mary'
keyof
A new function that can be used in a root. Same as keyof T
in Typescript.
NOTE: currently works only with objects only, this behavior will be fixed in future releases.
Example:
import s from 'ajv-ts';
cosnt keys = s.keyof(s.object({
key1: s.string(),
key2: s.object({})
}));
type Result = s.infer<typeof keys> // 'key1' | 'key2'
keys.schema // { anyOf: [ { cosnt: 'key1' }, {const: 'key2' } ] }
Never
Same as never
type in Typescript. JSON-schema equivalent is {not: {}}
.
Fixes
s.number()
- now generic!s.boolean()
- now generic!
Array
empty schema definition
function can be called without schema definition
import s from 'ajv-ts'
// before 0.5
s.array() // error
// 0.5 and later
s.array() // OK, deinition is not required anymore!
addItems
push(append) schema to array(parent) schema.
Example:
import s from 'ajv-ts'
const empty = s.array()
const stringArr = empty.addItems(s.string())
stringArr.schema // {type: 'array', items: [{ type: 'string' }]}
minContains/maxContains
Improve typescript generics usage. Now you cannot set float or negative values.
Example:
import s from 'ajv-ts'
// Before 0.5
s.array(s.number()).minContains(-1) // Typescript was silent
// After 0.5
s.array(s.number()).minContains(-1) // Typescript error: `Argument of type 'number' is not assignable to parameter of type '[never, 'TypeError: "minContains" should be positive integer', "Received: '-1'"]'.`
JS Doc updates
Update and add JS Doc for:
schema.nullable()
- updatearray()
- updateschema.validate()
- updateparse
- updatenumber().const()
- updatearray().contains()
- addconst()
- addany()
- updateunknown()
- updatecreate()
- update
Subscribe to my newsletter
Read articles from Vitali Haradkou directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Vitali Haradkou
Vitali Haradkou
SDET. Certified Node.js Application Developer(JSNAD)