io-ts-types
Version:
A collection of codecs and combinators for use with io-ts
58 lines (57 loc) • 2.26 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.either = void 0;
var t = __importStar(require("io-ts"));
var leftLiteral = t.literal('Left');
var rightLiteral = t.literal('Right');
/**
* Given a codec representing a type `L` and a codec representing a type `A`, returns a codec representing `Either<L, A>` that is able to deserialize
* the JSON representation of an `Either`.
*
* @example
* import { either } from 'io-ts-types/lib/either'
* import { left, right } from 'fp-ts/lib/Either'
* import * as t from 'io-ts'
* import { PathReporter } from 'io-ts/lib/PathReporter'
*
* const T = either(t.string, t.number)
*
* assert.deepStrictEqual(T.decode(right(1)), right(right(1)))
* assert.deepStrictEqual(T.decode(left('a')), right(left('a')))
* assert.deepStrictEqual(PathReporter.report(T.decode(right('a'))), ['Invalid value "a" supplied to : Either<string, number>/1: Right<string>/right: number'])
*
* @since 0.5.0
*/
function either(leftCodec, rightCodec, name) {
if (name === void 0) { name = "Either<" + leftCodec.name + ", " + rightCodec.name + ">"; }
return t.union([
t.strict({
_tag: leftLiteral,
left: leftCodec
}, "Left<" + leftCodec.name + ">"),
t.strict({
_tag: rightLiteral,
right: rightCodec
}, "Right<" + leftCodec.name + ">")
], name);
}
exports.either = either;
;