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.
A value of type Type<T>
(called "runtime type") is the runtime representation of the static type T
:
class Type<T> {
constructor(public readonly name: string, public readonly validate: Validate<T>) {}
is(x: any): x is T
}
where Validate<T>
is a specific validation function for T
type Validate<T> = (value: any, context: Context) => Either<Array<ValidationError>, T>;
Example
A runtime type representing string
can be defined as
import { Right, Left } from 'fp-ts/lib/Either'
import * as t from 'io-ts'
const string = new t.Type<string>(
'string',
(value, context) => typeof value === 'string' ? new Right(value) : new Left([{ value, context }])
)
A runtime type can be used to validate an object in memory (for example an API payload)
const Person = t.interface({
name: t.string,
age: t.number
})
// ok
t.validate(JSON.parse('{"name":"Giulio","age":43}'), Person) // => Right({name: "Giulio", age: 43})
// ko
t.validate(JSON.parse('{"name":"Giulio"}'), Person) // => Left([...])
A reporter implements the following interface
interface Reporter<A> {
report: (validation: Validation<any>) => A;
}
This package exports two default reporters
PathReporter: Reporter<Array<string>>
ThrowReporter: Reporter<void>
Example
import { PathReporter, ThrowReporter } from '../src/reporters/default'
const validation = t.validate({"name":"Giulio"}, Person)
console.log(PathReporter.report(validation))
// => ['Invalid value undefined supplied to : { name: string, age: number }/age: number']
ThrowReporter.report(validation)
// => throws 'Invalid value undefined supplied to : { name: string, age: number }/age: number'
Runtime types 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 runtime types with the TypeOf
operator
type IPerson = t.TypeOf<typeof Person>
// same as
type IPerson = {
name: string,
age: number
}
Note that recursive types can't be inferred
// helper type
type ICategory = {
name: string,
categories: Array<ICategory>
}
const Category = t.recursion<ICategory>('Category', self => t.object({
name: t.string,
categories: t.array(self)
}))
import * as t from 'io-ts'
Type | TypeScript annotation syntax | Runtime type / combinator |
---|---|---|
null | null | t.null |
undefined | undefined | t.undefined |
string | string | t.string |
number | number | t.number |
integer | ✘ | t.Integer |
boolean | boolean | t.boolean |
generic array | Array<any> | t.Array |
generic dictionary | { [key: string]: any } | t.Dictionary |
function | Function | t.Function |
instance of C | C | t.instanceOf(C) |
arrays | Array<A> | t.array(A) |
literal | 's' | t.literal('s') |
maybe | `A | undefined |
dictionaries | { [key: A]: B } | t.dictionary(A, B) |
refinement | ✘ | t.refinement(A, predicate) |
interface | { name: string } | t.interface({ name: t.string }) |
tuple | [A, B] | t.tuple([A, B]) |
union | `A | B` |
intersection | A & B | t.intersection([A, B]) |
keyof | keyof M | t.keyof(M) |
recursive types | t.recursion(name, definition) |
0.1.0
New Feature
Integer
typeBreaking Changes
t.Object
type. Renamed to t.Dictionary
, now accepts arrays so is fully equivalent to { [key: string]: any }
.t.instanceOf
combinator. Removed.t.object
combinator. Renamed to t.interface
. ObjectType
to InterfaceType
. Excess properties are now pruned.mapping
combinator. Renamed to dictionary
. MappingType
to DictionaryType
.intersection
combinator. Due to the new excess property pruning in t.interface
now only accept InterfaceType
s.isSuccess
removed, use either.isRight
insteadisFailure
removed, use either.isLeft
insteadfromValidation
removedFAQs
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.