io-ts-types
Version:
A collection of codecs and combinators for use with io-ts
51 lines (50 loc) • 1.99 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.fromNullable = void 0;
/**
* @since 0.5.0
*/
var t = __importStar(require("io-ts"));
var withValidate_1 = require("./withValidate");
/**
* Returns a clone of the given codec that replace a nullable input with the given value `a`
*
* @example
* import { fromNullable } from 'io-ts-types/lib/fromNullable'
* import * as t from 'io-ts'
* import { right } from 'fp-ts/lib/Either'
* import { PathReporter } from 'io-ts/lib/PathReporter'
*
* const T = fromNullable(t.number, -1)
*
* assert.deepStrictEqual(T.decode(1), right(1))
* assert.deepStrictEqual(T.decode(null), right(-1))
* assert.deepStrictEqual(T.decode(undefined), right(-1))
* assert.deepStrictEqual(PathReporter.report(T.decode('a')), ['Invalid value "a" supplied to : fromNullable(number)'])
*
* @since 0.5.0
*/
function fromNullable(codec, a, name) {
if (name === void 0) { name = "fromNullable(" + codec.name + ")"; }
return withValidate_1.withValidate(codec, function (u, c) { return (u == null ? t.success(a) : codec.validate(u, c)); }, name);
}
exports.fromNullable = fromNullable;
;