io-ts-types
Version:
A collection of codecs and combinators for use with io-ts
57 lines (56 loc) • 2.18 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.fromNewtype = void 0;
/**
* @since 0.5.2
*/
var newtype_ts_1 = require("newtype-ts");
var t = __importStar(require("io-ts"));
var pipeable_1 = require("fp-ts/lib/pipeable");
var Either_1 = require("fp-ts/lib/Either");
/**
* Returns a codec from a newtype
*
* @example
* import { fromNewtype } from 'io-ts-types/lib/fromNewtype'
* import * as t from 'io-ts'
* import { right } from 'fp-ts/lib/Either'
* import { PathReporter } from 'io-ts/lib/PathReporter'
* import { Newtype, iso } from 'newtype-ts'
*
* interface Token extends Newtype<{ readonly Token: unique symbol }, string> {}
*
* const T = fromNewtype<Token>(t.string)
*
* assert.deepStrictEqual(T.decode('sometoken'), right(iso<Token>().wrap('sometoken')))
* assert.deepStrictEqual(PathReporter.report(T.decode(42)), ['Invalid value 42 supplied to : fromNewtype(string)'])
*
* @since 0.5.2
*/
function fromNewtype(codec, name) {
if (name === void 0) { name = "fromNewtype(" + codec.name + ")"; }
var i = newtype_ts_1.iso();
return new t.Type(name, function (u) { return codec.is(u); }, function (u, c) {
return pipeable_1.pipe(codec.validate(u, c), Either_1.map(i.wrap));
}, function (a) { return codec.encode(i.unwrap(a)); });
}
exports.fromNewtype = fromNewtype;
;