Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
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>;
Note. The Either
type is defined in fp-ts, a library containing implementations of common algebraic types in TypeScript.
Example
A runtime type representing string
can be defined as
import * as t from 'io-ts'
const string = new t.Type<string>(
'string',
(value, context) => typeof value === 'string' ? t.success(v) : t.failure<string>(v, c)
)
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 'io-ts/lib/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 |
boolean | boolean | t.boolean |
any | any | t.any |
never | never | t.never |
integer | ✘ | t.Integer |
generic array | Array<any> | t.Array |
generic dictionary | { [key: string]: any } | t.Dictionary |
function | Function | t.Function |
arrays | Array<A> | t.array(A) |
literal | 's' | t.literal('s') |
maybe | `A | null` |
partial | Partial<{ name: string }> | t.partial({ name: t.string }) |
readonly | Readonly<{ name: string }> | t.readonly({ name: t.string }) |
readonly array | ReadonlyArray<number> | t.readonlyArray(t.number) |
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 | t.union([A, B]) |
intersection | A & B | t.intersection([A, B]) |
keyof | keyof M | t.keyof(M) |
recursive types | t.recursion(name, definition) | |
map | ✘ | t.map(f, type) |
prism | ✘ | t.prism(type, getOption) |
Note. You can mix required and optional props using an intersection
const A = t.interface({
foo: t.string
})
const B = t.partial({
bar: t.number
})
const C = t.intersection([A, B])
type CT = t.TypeOf<typeof C>
// same as
type CT = {
foo: string,
bar?: number
}
You can define your own types. Let's see an example
import * as t from 'io-ts'
// returns a Date from an ISO string
const DateFromString = new t.Type<Date>(
'DateFromString',
(v, c) => t.string.validate(v, c).chain(s => {
const d = new Date(s)
return isNaN(d.getTime()) ? t.failure<Date>(s, c) : t.success(d)
})
)
const s = new Date(1973, 10, 30).toISOString()
t.validate(s, DateFromString)
// => Right(Date(..))
t.validate('foo', DateFromString)
// => Left( 'Invalid value "foo" supplied to : DateFromString' )
Note that you can deserializing while validating.
You can define your own combinators. Let's see some examples
maybe
combinatorexport function maybe<RT extends t.Any>(type: RT, name?: string): t.UnionType<[RT, typeof t.null], t.TypeOf<RT> | null> {
return t.union([type, t.null], name)
}
brand
combinatorThe problem
const payload = {
celsius: 100,
fahrenheit: 100
}
const Payload = t.interface({
celsius: t.number,
fahrenheit: t.number
})
// x can be anything
function naiveConvertFtoC(x: number): number {
return (x - 32) / 1.8;
}
// typo: celsius instead of fahrenheit
console.log(t.validate(payload, Payload).map(x => naiveConvertFtoC(x.celsius))) // NO error :(
Solution (branded types)
export function brand<T, B extends string>(type: t.Type<T>, brand: B): t.Type<T & { readonly __brand: B }> {
return type as any
}
const Fahrenheit = brand(t.number, 'Fahrenheit')
const Celsius = brand(t.number, 'Celsius')
type CelsiusT = t.TypeOf<typeof Celsius>
type FahrenheitT = t.TypeOf<typeof Fahrenheit>
const Payload2 = t.interface({
celsius: Celsius,
fahrenheit: Fahrenheit
})
// narrowed types
function convertFtoC(fahrenheit: FahrenheitT): CelsiusT {
return (fahrenheit - 32) / 1.8 as CelsiusT;
}
console.log(t.validate(payload, Payload2).map(x => convertFtoC(x.celsius))) // error: Type '"Celsius"' is not assignable to type '"Fahrenheit"'
console.log(t.validate(payload, Payload2).map(x => convertFtoC(x.fahrenheit))) // ok
No, however you can define your own logic for that (if you really trust the input)
import * as t from 'io-ts'
import { pathReporterFailure } from 'io-ts/lib/reporters/default'
function unsafeValidate<T>(value: any, type: t.Type<T>): T {
if (process.env.NODE_ENV !== 'production') {
return t.validate(value, type)
.fold(
errors => { throw new Error(pathReporterFailure(errors).join('\n')) },
x => x
)
}
return value as T
}
Due to an upstream bug, VS Code might display weird types for nested interfaces
const NestedInterface = t.interface({
foo: t.interface({
bar: t.string
})
});
type NestedInterfaceType = t.TypeOf<typeof NestedInterface>;
/*
Hover on NestedInterfaceType will display
type NestedInterfaceType = {
foo: t.InterfaceOf<{
bar: t.Type<string>;
}>;
}
instead of
type NestedInterfaceType = {
foo: {
bar: string;
};
}
*/
0.4.0
fp-ts
(io-ts
APIs are not changed though) (@gcanti)lib-jsnext
folderFAQs
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
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
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.