How to use the io-ts.Type function in io-ts

To help you get started, we’ve selected a few io-ts examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tangdrew / fhir-ts / packages / primitives / src / R4 / id.ts View on Github external
* ID FHIR Primitive Runtime Type
 */

import { Type, success, failure, identity, TypeOf } from "io-ts";

// TODO: This regex seems incorrect as well
const ID_REGEX = /[A-Za-z0-9\-\.]{1,64}/;

const isId = (m: unknown): m is string =>
  typeof m === "string" && ID_REGEX.test(m);

/**
 * Any combination of upper- or lower-case ASCII letters ('A'..'Z', and 'a'..'z', numerals ('0'..'9'),
 * '-' and '.', with a length limit of 64 characters.
 */
export const id = new Type(
  "id",
  isId,
  (m, c) => (isId(m) ? success(m) : failure(m, c)),
  identity
);

export type id = TypeOf;
github yahiaetman / Go-Server / src / types / color.codec.ts View on Github external
import * as io from 'io-ts';
import * as t from './color.type';

export const Color = new io.Type(
    "Color",
    (u: any): u is t.Color => u in [t.Color.BLACK, t.Color.WHITE, t.Color.NONE],
    (i: unknown, c: io.Context) => {
        if(typeof i === 'string') {
            switch(i.toUpperCase()){
                case t.Color.BLACK: return io.success(t.Color.BLACK);
                case t.Color.WHITE: return io.success(t.Color.WHITE);
                case t.Color.NONE: return io.success(t.Color.NONE);
                default: return io.failure(i, c, `Unknown Color ${i}`);
            }
        } else return io.failure(i, c, `${i} must be a string`);
    },
    (u: t.Color): string => u
);
github gcanti / io-ts-types / src / newtype-ts / fromRefinement.ts View on Github external
) =&gt; Type = <s>() =&gt; (
  carrier: Type, O, unknown&gt;,
  prism: Prism, S&gt;,
  name: string = `Refinement&lt;${carrier.name}&gt;`
) =&gt;
  new Type(
    name,
    (u): u is S =&gt; carrier.is(u) &amp;&amp; prism.getOption(u).isSome(),
    (u, c) =&gt; carrier.validate(u, c).chain(s =&gt; prism.getOption(s).foldL(() =&gt; failure(s, c), success)),
    a =&gt; carrier.encode(a)
  )
</s>
github gcanti / fp-ts-routing / src / index.ts View on Github external
* @example
 * import { str, Route } from 'fp-ts-routing'
 * import { some, none } from 'fp-ts/lib/Option'
 *
 * assert.deepStrictEqual(str('id').parser.run(Route.parse('/abc')), some([{ id: 'abc' }, new Route([], {})]))
 * assert.deepStrictEqual(str('id').parser.run(Route.parse('/')), none)
 * @since 0.4.0
 */
export function str(k: K): Match&lt;{ [_ in K]: string }&gt; {
  return type(k, string)
}

/**
 * @internal
 */
export const IntegerFromString = new Type(
  'IntegerFromString',
  (u): u is number =&gt; Int.is(u),
  (u, c) =&gt;
    either.chain(string.validate(u, c), s =&gt; {
      const n = +s
      return isNaN(n) || !Number.isInteger(n) ? failure(s, c) : success(n)
    }),
  String
)

/**
 * `int` matches any integer path component
 *
 * @example
 * import { int, Route } from 'fp-ts-routing'
 * import { some, none } from 'fp-ts/lib/Option'
github gcanti / io-ts-types / src / eitherFromJSON.ts View on Github external
export function eitherFromJSON(
  leftCodec: L,
  rightCodec: R,
  name: string = `Either&lt;${leftCodec.name}, ${rightCodec.name}&gt;`
): EitherFromJSONC {
  const leftC = t.type({
    value: leftCodec
  })
  const rightC = t.type({
    value: rightCodec
  })
  return new t.Type(
    name,
    (u): u is Either, t.TypeOf&gt; =&gt;
      (u instanceof Left &amp;&amp; leftCodec.is(u.value)) || (u instanceof Right &amp;&amp; rightCodec.is(u.value)),
    (u, c) =&gt;
      t.UnknownRecord.validate(u, c).chain(o =&gt; {
        if (o._tag === 'Left') {
          return leftC.validate(o, c).map(s =&gt; left(s.value))
        } else if (o._tag === 'Right') {
          return rightC.validate(o, c).map(s =&gt; right(s.value))
        } else {
          return t.failure(u, c)
        }
      }),
    a =&gt; a.fold(l =&gt; jleft(leftCodec.encode(l)), a =&gt; jright(rightCodec.encode(a)))
  )
}
github celo-org / celo-monorepo / packages / utils / src / io.ts View on Github external
export const JSONStringType = new t.Type(
  'JSONString',
  t.string.is,
  (input, context) =&gt;
    either.chain(t.string.validate(input, context), (stringValue) =&gt; {
      try {
        JSON.parse(stringValue)
        return t.success(stringValue)
      } catch (error) {
        return t.failure(stringValue, context, 'can not be parsed as JSON')
      }
    }),
  String
)

export const E164PhoneNumberType = new t.Type(
  'E164Number',
  t.string.is,
  (input, context) =&gt;
    either.chain(
      t.string.validate(input, context),
      (stringValue) =&gt;
        isE164NumberStrict(stringValue)
          ? t.success(stringValue)
          : t.failure(stringValue, context, 'is not a valid e164 number')
    ),
  String
)

export const AddressType = new t.Type(
  'Address',
  t.string.is,
github elastic / kibana / x-pack / legacy / plugins / apm / common / runtime_types / transaction_sample_rate_rt / index.ts View on Github external
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

import * as t from 'io-ts';

export const transactionSampleRateRt = new t.Type(
  'TransactionSampleRate',
  t.number.is,
  (input, context) =&gt; {
    const value = parseFloat(input as string);
    return value &gt;= 0 &amp;&amp; value &lt;= 1 &amp;&amp; parseFloat(value.toFixed(3)) === value
      ? t.success(value)
      : t.failure(input, context);
  },
  t.identity
);
github teamdigitale / io-functions / lib / utils / types.ts View on Github external
.map(
            key =&gt;
              !props.hasOwnProperty(key)
                ? t.getValidationError(o[key], t.appendContext(c, key, t.never))
                : undefined
          )
          .filter((e): e is t.ValidationError =&gt; e !== undefined);
        return errors.length ? t.failures(errors) : t.success(o);
      }),
    loose.encode
  );
}

const isDate = (v: t.mixed): v is Date =&gt; v instanceof Date;

export const DateFromString = new t.Type(
  "DateFromString",
  isDate,
  (v, c) =&gt;
    isDate(v)
      ? t.success(v)
      : t.string.validate(v, c).chain(s =&gt; {
          const d = new Date(s);
          return isNaN(d.getTime()) ? t.failure(s, c) : t.success(d);
        }),
  a =&gt; a.toISOString()
);

export type DateFromString = t.TypeOf;
github Dragory / ZeppelinBot / backend / src / utils.ts View on Github external
dropPropertiesByName(value, propName);
    }
  }
}

export const tAlphanumeric = new t.Type(
  "tAlphanumeric",
  (s): s is string =&gt; typeof s === "string",
  (from, to) =&gt;
    either.chain(t.string.validate(from, to), s =&gt; {
      return s.match(/\W/) ? t.failure(from, to, "String must be alphanumeric") : t.success(s);
    }),
  s =&gt; s,
);

export const tDateTime = new t.Type(
  "tDateTime",
  (s): s is string =&gt; typeof s === "string",
  (from, to) =&gt;
    either.chain(t.string.validate(from, to), s =&gt; {
      const parsed =
        s.length === 10 ? moment(s, "YYYY-MM-DD") : s.length === 19 ? moment(s, "YYYY-MM-DD HH:mm:ss") : null;

      return parsed &amp;&amp; parsed.isValid() ? t.success(s) : t.failure(from, to, "Invalid datetime");
    }),
  s =&gt; s,
);

export const tDelayString = new t.Type(
  "tDelayString",
  (s): s is string =&gt; typeof s === "string",
  (from, to) =&gt;
github gcanti / money-ts / src / io-ts / PositiveRational.ts View on Github external
import { Type, mixed, tuple } from 'io-ts'
import { Natural } from './Natural'
import { PositiveRational as PositiveRationalNewtype, reduce } from '../PositiveRational'

const PR = tuple([Natural, Natural])

export const PositiveRational: Type = new Type(
  'PositiveRational',
  PR.is,
  (m, c) =&gt; PR.validate(m, c).map(([n, d]) =&gt; reduce(n, d)),
  PR.encode
)