Socket
Socket
Sign inDemoInstall

io-ts

Package Overview
Dependencies
1
Maintainers
1
Versions
120
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

io-ts


Version published
Maintainers
1
Install size
643 kB
Created

Package description

What is io-ts?

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.

What are io-ts's main functionalities?

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"}

Other packages similar to io-ts

Changelog

Source

0.9.3

  • Bug Fix
    • revert 37c74a5e2038de063a950f9ba8d18b1f132ef450, closes #8 (@gcanti)

Readme

Source

The idea

A value of type Type<S, A> (called "runtime type") is the runtime representation of the static type A:

class Type<S, A> {
  readonly _A: A
  readonly _S: S
  constructor(
    readonly name: string,
    readonly is: Is<A>,
    readonly validate: Validate<S, A>,
    readonly serialize: Serialize<S, A>
  ) {}
}

where Validate<A> is a specific validation function for the type A

export interface ContextEntry {
  readonly key: string
  readonly type: Any | NeverType
}
export type Context = Array<ContextEntry>
export interface ValidationError {
  readonly value: any
  readonly context: Context
}
export type Errors = Array<ValidationError>
export type Validation<A> = Either<Errors, A>
export type Is<A> = (v: any) => v is A
export type Validate<S, A> = (s: S, context: Context) => Validation<A>
export type Serialize<S, A> = (a: A) => S

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'

export class StringType extends Type<any, string> {
  constructor() {
    super(
      'string',
      (v): v is string => typeof v === 'string',
      (s, c) => (this.is(s) ? success(s) : failure(s, c)),
      a => a
    )
  }
}

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([...])

Error reporters

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 } from 'io-ts/lib/PathReporter'
import { ThrowReporter } from 'io-ts/lib/ThrowReporter'

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'

Community

TypeScript integration

Runtime types can be inspected

instrospection

This library uses TypeScript extensively. Its API is defined in a way which automatically infers types for produced values

inference

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
}

Recursive types

Recursive types can't be inferred by TypeScript so you must provide the static type as a hint

// helper type
type ICategory = {
  name: string,
  categories: Array<ICategory>
}

const Category =
  t.recursion <
  ICategory >
  ('Category',
  self =>
    t.interface({
      name: t.string,
      categories: t.array(self)
    }))

Implemented types / combinators

import * as t from 'io-ts'
TypeTypeScriptFlowRuntime type / combinator
nullnullnullt.null or t.nullType
undefinedundefinedvoidt.undefined
stringstringstringt.string
numbernumbernumbert.number
booleanbooleanbooleant.boolean
anyanyanyt.any
neverneveremptyt.never
objectobjectt.object
integert.Integer
array of anyArray<any>Array<any>t.Array
array of typeArray<A>Array<A>t.array(A)
dictionary of any{ [key: string]: any }{ [key: string]: any }t.Dictionary
dictionary of type{ [K in A]: B }{ [key: A]: B }t.dictionary(A, B)
functionFunctionFunctiont.Function
literal's''s't.literal('s')
partialPartial<{ name: string }>$Shape<{ name: string }>t.partial({ name: t.string })
readonlyReadonly<T>ReadOnly<T>t.readonly(T)
readonly arrayReadonlyArray<number>ReadOnlyArray<number>t.readonlyArray(t.number)
interfaceinterface A { name: string }interface A { name: string }t.interface({ name: t.string }) or t.type({ name: t.string })
interface inheritanceinterface B extends A {}interface B extends A {}t.intersection([ A, t.interface({}) ])
tuple[ A, B ][ A, B ]t.tuple([ A, B ])
unionA | BA | Bt.union([ A, B ])
intersectionA & BA & Bt.intersection([ A, B ])
keyofkeyof M$Keys<M>t.keyof(M)
recursive typessee Recursive typessee Recursive typest.recursion(name, definition)
refinementt.refinement(A, predicate)
strict/exact types$Exact<{{ name: t.string }}>t.strict({ name: t.string })

Refinements

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')

Strict/Exact interfaces

You can make an interface strict (which means that only the given properties are allowed) using the strict combinator

const Person = t.interface({
  name: t.string,
  age: t.number
})

const StrictPerson = t.strict(Person.props)

t.validate({ name: 'Giulio', age: 43, surname: 'Canti' }, Person) // ok
t.validate({ name: 'Giulio', age: 43, surname: 'Canti' }, StrictPerson) // fails

Mixing required and optional props

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
}

Custom types

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<any, Date>(
  'DateFromString',
  (v): v is Date => v instanceof Date,
  (v, c) =>
    t.string.validate(v, 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()

t.validate(s, DateFromString)
// right(new Date('1973-11-29T23:00:00.000Z'))

t.validate('foo', DateFromString)
// left(errors...)

Note that you can deserialize while validating.

Custom combinators

You can define your own combinators. Let's see some examples

The maybe combinator

An equivalent to T | null

export function maybe<RT extends t.Any>(type: RT, name?: string): t.UnionType<[RT, t.NullType], t.TypeOf<RT> | null> {
  return t.union<[RT, t.NullType]>([type, t.null], name)
}

Recipes

Is there a way to turn the checks off in production code?

No, however you can define your own logic for that (if you really trust the input)

import * as t from 'io-ts'
import { failure } from 'io-ts/lib/PathReporter'

const { NODE_ENV } = process.env

export function unsafeValidate<S, A>(value: any, type: t.Type<S, A>): A {
  if (NODE_ENV !== 'production') {
    return t.validate(value, type).fold(errors => {
      throw new Error(failure(errors).join('\n'))
    }, t.identity)
  }
  // unsafe cast
  return value as A
}

Known issues

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.StringType;
  }>;
}

instead of

type NestedInterfaceType = {
  foo: {
    bar: string;
  };
}
*/

Keywords

FAQs

Last updated on 23 Dec 2017

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc