UNPKG

io-ts-types

Version:

A collection of codecs and combinators for use with io-ts

49 lines (48 loc) 1.84 kB
"use strict"; 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.withFallback = void 0; /** * @since 0.5.0 */ var t = __importStar(require("io-ts")); var withValidate_1 = require("./withValidate"); var Either_1 = require("fp-ts/lib/Either"); /** * Returns a clone of the given codec that always succeed using the given value `a` if the original codec fails * * @example * import { withFallback } from 'io-ts-types/lib/withFallback' * import * as t from 'io-ts' * import { right } from 'fp-ts/lib/Either' * * const T = withFallback(t.number, -1) * * assert.deepStrictEqual(T.decode(1), right(1)) * assert.deepStrictEqual(T.decode('a'), right(-1)) * * @since 0.5.0 */ function withFallback(codec, a, name) { if (name === void 0) { name = "withFallback(" + codec.name + ")"; } return withValidate_1.withValidate(codec, function (u, c) { return Either_1.orElse(function () { return t.success(a); })(codec.validate(u, c)); }, name); } exports.withFallback = withFallback;