Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
The io-ts npm package is a TypeScript library that allows for the definition of runtime types, and the automatic validation of runtime values against those types. It leverages TypeScript's type system to ensure that data structures conform to specified schemas, providing a bridge between the runtime data and compile-time types.
Runtime type validation
This feature allows you to define a type and then validate an object against that type at runtime. If the object matches the type, the 'Right' branch is executed; otherwise, the 'Left' branch indicates a validation error.
{"const t = require('io-ts');\nconst User = t.type({\n name: t.string,\n age: t.number\n});\nconst result = User.decode({ name: 'Alice', age: 25 });\nif (result._tag === 'Right') {\n console.log('Valid!', result.right);\n} else {\n console.log('Invalid!', result.left);\n}"}
Type composition
io-ts allows for the composition of types, enabling complex type definitions by combining simpler ones. This is useful for building up the shape of data structures from reusable type components.
{"const t = require('io-ts');\nconst Name = t.string;\nconst Age = t.number;\nconst User = t.type({ name: Name, age: Age });\nconst result = User.decode({ name: 'Bob', age: 'not-a-number' });\n// result will be an instance of Left since 'age' is not a number"}
Custom types
io-ts allows the creation of custom types with additional validation logic. In this example, a 'PositiveNumber' type is created that only accepts positive numbers.
{"const t = require('io-ts');\nconst PositiveNumber = t.brand(\n t.number,\n (n): n is t.Branded<number, { readonly PositiveNumber: unique symbol }> => n > 0,\n 'PositiveNumber'\n);\nconst result = PositiveNumber.decode(-5);\n// result will be an instance of Left since the number is not positive"}
Ajv is a JSON schema validator that provides runtime data validation using predefined JSON schemas. It is similar to io-ts in that it validates data structures at runtime, but it uses JSON schema as the basis for validation rather than TypeScript types.
Joi is an object schema validation library that allows for the description and validation of JavaScript objects. It is similar to io-ts in providing runtime validation, but it uses a fluent API for schema definition and does not integrate with TypeScript types in the same way.
Yup is a JavaScript schema builder for value parsing and validation. It defines a schema using a declarative API and validates objects against the schema. Like io-ts, it provides runtime validation, but it does not leverage TypeScript's type system for type definitions.
Class-validator allows for validation of class instances based on decorators. It is similar to io-ts in that it provides runtime validation, but it is designed to work with classes and decorators, offering a different approach to defining validation rules.
Blog post: "Typescript and validations at runtime boundaries" by @lorefnon
A value of type Type<A, O, I>
(called "codec") is the runtime representation of the static type A
.
Also a codec can
I
(through decode
)O
(through encode
)is
)export type mixed = unknown
class Type<A, O = A, I = mixed> {
readonly _A: A
readonly _O: O
readonly _I: I
constructor(
/** a unique name for this codec */
readonly name: string,
/** a custom type guard */
readonly is: (v: mixed) => v is A,
/** succeeds if a value of type I can be decoded to a value of type A */
readonly validate: (input: I, context: Context) => Either<Errors, A>,
/** converts a value of type A to a value of type O */
readonly encode: (a: A) => O
) {}
/** a version of `validate` with a default context */
decode(i: I): Either<Errors, A>
}
Note. The Either
type is defined in fp-ts, a library containing implementations of
common algebraic types in TypeScript.
Example
A codec representing string
can be defined as
import * as t from 'io-ts'
// codec definition
export class StringType extends t.Type<string> {
// equivalent to Type<string, string, mixed> as per type parameter defaults
readonly _tag: 'StringType' = 'StringType'
constructor() {
super(
'string',
(m): m is string => typeof m === 'string',
(m, c) => (this.is(m) ? t.success(m) : t.failure(m, c)),
t.identity
)
}
}
// codec instance: use this when building other codecs instances
export const string = new StringType()
A codec can be used to validate an object in memory (for example an API payload)
const Person = t.type({
name: t.string,
age: t.number
})
// validation succeeded
Person.decode(JSON.parse('{"name":"Giulio","age":43}')) // => Right({name: "Giulio", age: 43})
// validation failed
Person.decode(JSON.parse('{"name":"Giulio"}')) // => Left([...])
io-ts version | required TypeScript version |
---|---|
1.6.x | 3.2.2+ |
1.5.3 | 3.0.1+ |
1.5.2- | 2.7.2+ |
Note. If you are running < typescript@3.0.1
you have to polyfill unknown
.
You can use unknown-ts as a polyfill.
A reporter implements the following interface
interface Reporter<A> {
report: (validation: Validation<any>) => A
}
This package exports a default PathReporter
reporter
Example
import { PathReporter } from 'io-ts/lib/PathReporter'
const result = Person.decode({ name: 'Giulio' })
console.log(PathReporter.report(result))
// => ['Invalid value undefined supplied to : { name: string, age: number }/age: number']
You can define your own reporter. Errors
has the following type
interface ContextEntry {
readonly key: string
readonly type: Decoder<any, any>
}
interface Context extends ReadonlyArray<ContextEntry> {}
interface ValidationError {
readonly value: mixed
readonly context: Context
}
interface Errors extends Array<ValidationError> {}
Example
import * as t from 'io-ts'
const getPaths = <A>(v: t.Validation<A>): Array<string> => {
return v.fold(errors => errors.map(error => error.context.map(({ key }) => key).join('.')), () => ['no errors'])
}
const Person = t.type({
name: t.string,
age: t.number
})
console.log(getPaths(Person.decode({}))) // => [ '.name', '.age' ]
codecs can be inspected
This library uses TypeScript extensively. Its API is defined in a way which automatically infers types for produced values
Note that the type annotation isn't needed, TypeScript infers the type automatically based on a schema.
Static types can be extracted from codecs using the TypeOf
operator
type Person = t.TypeOf<typeof Person>
// same as
type Person = {
name: string
age: number
}
import * as t from 'io-ts'
Type | TypeScript | codec / combinator |
---|---|---|
null | null | t.null or t.nullType |
undefined | undefined | t.undefined |
void | void | t.void or t.voidType |
string | string | t.string |
number | number | t.number |
boolean | boolean | t.boolean |
any | any | t.any |
never | never | t.never |
object | object | t.object |
integer | ✘ | t.Integer |
array of any | Array<mixed> | t.Array |
array of type | Array<A> | t.array(A) |
dictionary of any | { [key: string]: mixed } | t.Dictionary |
dictionary of type | { [K in A]: B } | t.dictionary(A, B) |
function | Function | t.Function |
literal | 's' | t.literal('s') |
partial | Partial<{ name: string }> | t.partial({ name: t.string }) |
readonly | Readonly<T> | t.readonly(T) |
readonly array | ReadonlyArray<number> | t.readonlyArray(t.number) |
type alias | type A = { name: string } | t.type({ name: t.string }) |
tuple | [ A, B ] | t.tuple([ A, B ]) |
union | A | B | t.union([ A, B ]) or t.taggedUnion(tag, [ A, B ]) |
intersection | A & B | t.intersection([ A, B ]) |
keyof | keyof M | t.keyof(M) |
recursive types | see Recursive types | t.recursion(name, definition) |
refinement | ✘ | t.refinement(A, predicate) |
exact types | ✘ | t.exact(type) |
strict types (deprecated) | ✘ | t.strict({ name: t.string }) |
Recursive types can't be inferred by TypeScript so you must provide the static type as a hint
// helper type
interface ICategory {
name: string
categories: Array<ICategory>
}
const Category = t.recursion<ICategory>('Category', Category =>
t.type({
name: t.string,
categories: t.array(Category)
})
)
interface IFoo {
type: 'Foo'
b: IBar | undefined
}
interface IBar {
type: 'Bar'
a: IFoo | undefined
}
const Foo: t.RecursiveType<t.Type<IFoo>, IFoo> = t.recursion<IFoo>('Foo', _ =>
t.interface({
type: t.literal('Foo'),
b: t.union([Bar, t.undefined])
})
)
const Bar: t.RecursiveType<t.Type<IBar>, IBar> = t.recursion<IBar>('Bar', _ =>
t.interface({
type: t.literal('Bar'),
a: t.union([Foo, t.undefined])
})
)
const FooBar = t.taggedUnion('type', [Foo, Bar])
If you are encoding tagged unions, instead of the general purpose union
combinator, you may want to use the
taggedUnion
combinator in order to get better performances
const A = t.type({
tag: t.literal('A'),
foo: t.string
})
const B = t.type({
tag: t.literal('B'),
bar: t.number
})
// the actual presence of the tag is statically checked
const U = t.taggedUnion('tag', [A, B])
You can refine a type (any type) using the refinement
combinator
const Positive = t.refinement(t.number, n => n >= 0, 'Positive')
const Adult = t.refinement(Person, person => person.age >= 18, 'Adult')
You can make a codec alias exact (which means that only the given properties are allowed) using the exact
combinator
const Person = t.type({
name: t.string,
age: t.number
})
const ExactPerson = t.exact(Person)
Person.decode({ name: 'Giulio', age: 43, surname: 'Canti' }) // ok
ExactPerson.decode({ name: 'Giulio', age: 43, surname: 'Canti' }) // fails
Note. This combinator is deprecated, use exact
instead.
You can make a codec strict (which means that only the given properties are allowed) using the strict
combinator
const Person = t.type({
name: t.string,
age: t.number
})
const StrictPerson = t.strict(Person.props)
Person.decode({ name: 'Giulio', age: 43, surname: 'Canti' }) // ok
StrictPerson.decode({ name: 'Giulio', age: 43, surname: 'Canti' }) // fails
You can mix required and optional props using an intersection
const A = t.type({
foo: t.string
})
const B = t.partial({
bar: t.number
})
const C = t.intersection([A, B])
type C = t.TypeOf<typeof C>
// same as
type C = {
foo: string
} & {
bar?: number | undefined
}
You can apply partial
to an already defined codec via its props
field
const Person = t.type({
name: t.string,
age: t.number
})
const PartialPerson = t.partial(Person.props)
type PartialPerson = t.TypeOf<typeof PartialPerson>
// same as
type PartialPerson = {
name?: string
age?: number
}
You can define your own types. Let's see an example
import * as t from 'io-ts'
// represents a Date from an ISO string
const DateFromString = new t.Type<Date, string>(
'DateFromString',
(m): m is Date => m instanceof Date,
(m, c) =>
t.string.validate(m, c).chain(s => {
const d = new Date(s)
return isNaN(d.getTime()) ? t.failure(s, c) : t.success(d)
}),
a => a.toISOString()
)
const s = new Date(1973, 10, 30).toISOString()
DateFromString.decode(s)
// right(new Date('1973-11-29T23:00:00.000Z'))
DateFromString.decode('foo')
// left(errors...)
Note that you can deserialize while validating.
Polymorphic codecs are represented using functions. For example, the following typescript:
interface ResponseBody<T> {
result: T
_links: Links
}
interface Links {
previous: string
next: string
}
Would be:
import * as t from 'io-ts'
const ResponseBody = <RT extends t.Mixed>(type: RT) =>
t.interface({
result: type,
_links: Links
})
const Links = t.interface({
previous: t.string,
next: t.string
})
And used like:
const UserModel = t.type({
name: t.string
})
functionThatRequiresRuntimeType(ResponseBody(t.array(UserModel)), ...params)
You can pipe two codecs if their type parameters do align
const NumberDecoder = new t.Type<number, string, string>(
'NumberDecoder',
t.number.is,
(s, c) => {
const n = parseFloat(s)
return isNaN(n) ? t.failure(s, c) : t.success(n)
},
String
)
const NumberFromString = t.string.pipe(
NumberDecoder,
'NumberFromString'
)
No, however you can define your own logic for that (if you really trust the input)
import * as t from 'io-ts'
import { Either, right } from 'fp-ts/lib/Either'
const { NODE_ENV } = process.env
export function unsafeDecode<A, O, I>(value: I, type: t.Type<A, O, I>): Either<t.Errors, A> {
if (NODE_ENV !== 'production' || type.encode !== t.identity) {
return type.decode(value)
} else {
// unsafe cast
return right(value as any)
}
}
// or...
import { failure } from 'io-ts/lib/PathReporter'
export function unsafeGet<A, O, I>(value: I, type: t.Type<A, O, I>): A {
if (NODE_ENV !== 'production' || type.encode !== t.identity) {
return type.decode(value).getOrElseL(errors => {
throw new Error(failure(errors).join('\n'))
})
} else {
// unsafe cast
return value as any
}
}
Use keyof
instead of union
when defining a union of string literals
const Bad = t.union([
t.literal('foo'),
t.literal('bar'),
t.literal('baz')
// etc...
])
const Good = t.keyof({
foo: null,
bar: null,
baz: null
// etc...
})
Benefits
1.6.3
FAQs
TypeScript runtime type system for IO decoding/encoding
The npm package io-ts receives a total of 1,198,877 weekly downloads. As such, io-ts popularity was classified as popular.
We found that io-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.