### Install io-ts-types via npm Source: https://github.com/gcanti/io-ts-types/blob/master/README.md Use this command to install the stable version of the library in your project. ```sh npm i io-ts-types ``` -------------------------------- ### Use the option codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/option.ts.md Example demonstrating decoding of None and Some values using the option codec. ```ts import { option } from 'io-ts-types/lib/option' import { right } from 'fp-ts/lib/Either' import { none, some } from 'fp-ts/lib/Option' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' const T = option(t.number) assert.deepStrictEqual(T.decode(none), right(none)) assert.deepStrictEqual(T.decode(some(1)), right(some(1))) assert.deepStrictEqual(PathReporter.report(T.decode(some('a'))), [ 'Invalid value "a" supplied to : Option/1: Some/value: number' ]) ``` -------------------------------- ### Using fromNewtype with a Newtype Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromNewtype.ts.md Example demonstrating how to create a codec for a Newtype and use it for decoding. ```ts 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(t.string) assert.deepStrictEqual(T.decode('sometoken'), right(iso().wrap('sometoken'))) assert.deepStrictEqual(PathReporter.report(T.decode(42)), ['Invalid value 42 supplied to : fromNewtype(string)']) ``` -------------------------------- ### either Codec Usage Example Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/either.ts.md Demonstrates decoding Either values using the either codec. ```ts 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/1: Right/right: number' ]) ``` -------------------------------- ### fromNewtype Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromNewtype.ts.md This snippet details the `fromNewtype` function, its signature, and provides an example of its usage. ```APIDOC ## fromNewtype Function ### Description Returns a codec from a newtype. ### Signature ```ts export declare function fromNewtype(codec: t.Type, t.OutputOf>>, name?: string): t.Type, unknown> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts 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(t.string) // Example usage: // assert.deepStrictEqual(T.decode('sometoken'), right(iso().wrap('sometoken'))) // assert.deepStrictEqual(PathReporter.report(T.decode(42)), ['Invalid value 42 supplied to : fromNewtype(string)']) ``` ### Response #### Success Response (200) This function returns a codec of type `t.Type, unknown>`. #### Response Example ```json { "example": "Codec for a newtype" } ``` ``` -------------------------------- ### Use fromNullable with a codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromNullable.ts.md Example demonstrating how to use fromNullable to provide a default value for null or undefined inputs. ```ts 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)']) ``` -------------------------------- ### DateFromUnixTime Codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/DateFromUnixTime.ts.md The DateFromUnixTime codec implementation and an example of its usage. ```APIDOC ## DateFromUnixTime Codec ### Description This codec allows decoding a Unix timestamp (number) into a JavaScript Date object. It's useful for handling time-based data where timestamps are represented as numbers. ### Signature ```typescript export const DateFromUnixTime: DateFromUnixTimeC ``` ### Example ```typescript import { DateFromUnixTime } from 'io-ts-types/lib/DateFromUnixTime' import { right } from 'fp-ts/lib/Either' const date = new Date(1973, 10, 30) const input = date.getTime() / 1000 // Unix timestamp in seconds assert.deepStrictEqual(DateFromUnixTime.decode(input), right(date)) ``` ### Added in version v0.5.0 ``` -------------------------------- ### Transforming codec output with mapOutput Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/mapOutput.ts.md Example demonstrating how to use mapOutput to change the encoded output type of a codec from null to undefined. ```ts import * as t from 'io-ts' import { mapOutput } from 'io-ts-types/lib/mapOutput' import { optionFromNullable } from 'io-ts-types/lib/optionFromNullable' import { none, some } from 'fp-ts/lib/Option' // Input: t.Type, number | null, t.mixed> const Input = optionFromNullable(t.number) const toUndefined = (x: A | null): A | undefined => (x === null ? undefined : x) // Output: t.Type, number | undefined, t.mixed> const Output = mapOutput(Input, toUndefined) assert.strictEqual(Output.encode(none), undefined) assert.strictEqual(Output.encode(some(1)), 1) ``` -------------------------------- ### withValidate Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withValidate.ts.md This snippet details the `withValidate` function, its signature, and provides an example of its usage. ```APIDOC ## withValidate Function ### Description Returns a clone of the given codec which uses the given `validate` function. ### Signature ```ts export function withValidate(codec: C, validate: C['validate'], name: string = codec.name): C ``` ### Example ```ts import { withValidate } from 'io-ts-types/lib/withValidate' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import { either, right } from 'fp-ts/lib/Either' const T = withValidate(t.number, (u, c) => either.map(t.number.validate(u, c), n => n * 2)) assert.deepStrictEqual(T.decode(1), right(2)) assert.deepStrictEqual(PathReporter.report(T.decode(null)), ['Invalid value null supplied to : number']) ``` ``` -------------------------------- ### BigIntFromString Codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/BigIntFromString.ts.md The BigIntFromString codec provides a way to work with BigInt values represented as strings. It includes methods for decoding strings into BigInts and encoding BigInts back into strings. The examples demonstrate its usage with valid and invalid inputs. ```APIDOC ## BigIntFromString Codec ### Description Provides a codec for decoding strings into BigInt values and encoding BigInt values into strings. It handles validation to ensure the input string represents a valid BigInt. ### Method N/A (This is a codec definition, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "example": "1" } ``` ### Response #### Success Response (Decoding) - **bigint** (bigint) - The decoded BigInt value. #### Success Response (Encoding) - **string** (string) - The encoded string representation of the BigInt. #### Response Example (Decoding Success) ```json { "example": 1 } ``` #### Response Example (Encoding Success) ```json { "example": "1" } ``` #### Error Handling - **Invalid value supplied to : BigIntFromString** (string) - Returned when the input string cannot be parsed as a BigInt. #### Error Response Example ```json { "example": "Invalid value \"1.1\" supplied to : BigIntFromString" } ``` ``` -------------------------------- ### NonEmptyString Codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/NonEmptyString.ts.md This section details the NonEmptyString codec, which validates that a string is not empty. It includes its type definition, brand, and usage examples. ```APIDOC ## NonEmptyString Codec ### Description A codec that succeeds if a string is not empty. ### Method N/A (This is a type definition and codec) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```json { "example": "a" } ``` ### Response #### Success Response (200) - **value** (string) - The non-empty string if validation succeeds. #### Response Example ```json { "example": "a" } ``` ### Error Handling - **Invalid value supplied to : NonEmptyString** - Returned when an empty string is provided. ### Example Usage ```typescript import { NonEmptyString } from 'io-ts-types/lib/NonEmptyString' import { right } from 'fp-ts/lib/Either' import { PathReporter } from 'io-ts/lib/PathReporter' // Example of successful decoding assert.deepStrictEqual(NonEmptyString.decode('a'), right('a')) // Example of failed decoding with an empty string assert.deepStrictEqual(PathReporter.report(NonEmptyString.decode('')), [ 'Invalid value "" supplied to : NonEmptyString' ]) ``` ``` -------------------------------- ### Get Lenses for Codec Properties Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/getLenses.ts.md Use `getLenses` to obtain lenses for accessing and modifying properties of an io-ts codec. Ensure the codec is compatible with `HasLenses`. ```typescript import * as t from 'io-ts' import { getLenses } from 'io-ts-types/lib/getLenses' const Person = t.type({ name: t.string, age: t.number }) const lenses = getLenses(Person) assert.strictEqual(lenses.age.get({ name: 'Giulio', age: 44 }), 44) ``` -------------------------------- ### Add custom error message to a codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withMessage.ts.md Use withMessage to wrap a codec and provide a function that generates a custom error message. This function receives the input value and the codec context. The example demonstrates adding a message to a number codec. ```typescript import { withMessage } from 'io-ts-types/lib/withMessage' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import { right } from 'fp-ts/lib/Either' const T = withMessage(t.number, () => 'Invalid number') assert.deepStrictEqual(T.decode(1), right(1)) assert.deepStrictEqual(PathReporter.report(T.decode(null)), ['Invalid number']) ``` -------------------------------- ### Using withEncode to customize encoding Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withEncode.ts.md Demonstrates how to use withEncode to create a codec that encodes numbers to strings. Requires importing withEncode, io-ts, PathReporter, and Either. ```typescript import { withEncode } from 'io-ts-types/lib/withEncode' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import { right } from 'fp-ts/lib/Either' const T = withEncode(t.number, String) assert.deepStrictEqual(T.decode(1), right(1)) assert.deepStrictEqual(T.encode(1), '1') assert.deepStrictEqual(PathReporter.report(T.decode('str')), ['Invalid value "str" supplied to : number']) ``` -------------------------------- ### Create a codec from a refinement Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromRefinement.ts.md Defines a codec based on a provided type guard function. ```ts export function fromRefinement(name: string, is: (u: unknown) => u is A): t.Type { ... } ``` -------------------------------- ### mapFromEntries Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/mapFromEntries.ts.md The mapFromEntries function creates a codec for a Map from key and value codecs, along with an Ord instance for the keys. ```APIDOC ## mapFromEntries ### Description Creates a codec for a Map. ### Signature ```typescript export function mapFromEntries( keyCodec: K, KO: Ord>, valueCodec: V, name: string = `Map<${keyCodec.name}, ${valueCodec.name}>` ): MapFromEntriesC { ... } ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize BooleanFromNumber constant Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/BooleanFromNumber.ts.md Initializes the BooleanFromNumber codec instance. ```ts export const BooleanFromNumber: BooleanFromNumberC = ... ``` -------------------------------- ### function option Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/option.ts.md Creates a codec for an Option type based on a provided codec for the inner type. ```APIDOC ## function option ### Description Creates a codec representing Option that is able to deserialize the JSON representation of an Option. ### Parameters - **codec** (C extends t.Mixed) - Required - The codec representing the inner type A. - **name** (string) - Optional - The name of the codec, defaults to "Option<${codec.name}>". ### Request Example import { option } from 'io-ts-types/lib/option'; import * as t from 'io-ts'; const T = option(t.number); ``` -------------------------------- ### fromRefinement Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromRefinement.ts.md Returns a codec from a refinement. This function was added in v0.4.4. ```APIDOC ## fromRefinement ### Description Returns a codec from a refinement. ### Signature ```ts export declare function fromRefinement(name: string, is: (u: unknown) => u is A): t.Type ``` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the refinement. - **is** ((u: unknown) => u is A) - Required - The refinement function. ### Added in v0.4.4 ``` -------------------------------- ### Create mapFromEntries codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/mapFromEntries.ts.md Constructs a codec for a Map using key and value codecs along with an ordering instance. ```typescript export function mapFromEntries( keyCodec: K, KO: Ord>, valueCodec: V, name: string = `Map<${keyCodec.name}, ${valueCodec.name}>` ): MapFromEntriesC { ... } ``` -------------------------------- ### IntFromString Codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/IntFromString.ts.md Documentation for the IntFromString codec, which validates that a string can be parsed into an integer. ```APIDOC ## IntFromString Codec ### Description A codec that succeeds if a string can be parsed to an integer. It is exported as `IntFromString` and implements the `IntFromStringC` interface. ### Signature `export const IntFromString: IntFromStringC` ### Request Example ```ts import { IntFromString } from 'io-ts-types/lib/IntFromString' import { right } from 'fp-ts/lib/Either' // Successful decoding IntFromString.decode('1') // returns right(1) ``` ### Response #### Success Response - **value** (number) - The parsed integer if the input string is a valid integer. #### Error Response - **error** (string) - Returns an error message if the input string cannot be parsed as an integer (e.g., '1.1'). ``` -------------------------------- ### DateFromISOString Overview Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/DateFromISOString.ts.md Provides a codec for decoding ISO date strings into Date objects. ```APIDOC ## DateFromISOString Overview This module provides a codec for decoding ISO date strings into Date objects. ### Interface `DateFromISOStringC` is an interface that extends `t.Type`. ### Codec `DateFromISOString` is a codec that can be used to decode ISO date strings into `Date` objects. ### Example ```typescript import { DateFromISOString } from 'io-ts-types/lib/DateFromISOString' import { right } from 'fp-ts/lib/Either' const date = new Date(1973, 10, 30) const input = date.toISOString() assert.deepStrictEqual(DateFromISOString.decode(input), right(date)) ``` ``` -------------------------------- ### clone Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/clone.ts.md Returns a clone of the given codec. Added in v0.4.3. ```APIDOC ## clone overview Added in v0.4.3 --- # clone Returns a clone of the given codec **Signature** ```ts export function clone(t: C): C { ... } ``` **Example** ```ts import { clone } from 'io-ts-types/lib/clone' import * as t from 'io-ts' assert.deepStrictEqual(clone(t.string), t.string) ``` Added in v0.4.3 ``` -------------------------------- ### BooleanFromString Overview Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/BooleanFromString.ts.md Provides a codec for decoding strings 'true' and 'false' into their boolean equivalents. ```APIDOC ## BooleanFromString Overview This module provides a codec for decoding strings into booleans. It handles the string representations of `true` and `false`. ### Interface: BooleanFromStringC **Signature** ```typescript export interface BooleanFromStringC extends t.Type {} ``` ### Codec: BooleanFromString **Signature** ```typescript export const BooleanFromString: BooleanFromStringC = ... ``` ### Example Usage ```typescript import { BooleanFromString } from 'io-ts-types/lib/BooleanFromString' import { right } from 'fp-ts/lib/Either' import { PathReporter } from 'io-ts/lib/PathReporter' // Successful decoding assert.deepStrictEqual(BooleanFromString.decode('true'), right(true)) assert.deepStrictEqual(BooleanFromString.decode('false'), right(false)) // Failed decoding assert.deepStrictEqual(PathReporter.report(BooleanFromString.decode('a')), [ 'Invalid value "a" supplied to : BooleanFromString' ]) ``` ``` -------------------------------- ### Decode ISO string to Date Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/DateFromISOString.ts.md Demonstrates decoding an ISO 8601 string into a Date object using the DateFromISOString codec. ```ts import { DateFromISOString } from 'io-ts-types/lib/DateFromISOString' import { right } from 'fp-ts/lib/Either' const date = new Date(1973, 10, 30) const input = date.toISOString() assert.deepStrictEqual(DateFromISOString.decode(input), right(date)) ``` -------------------------------- ### Interface OptionC Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/option.ts.md The interface for the Option codec. ```APIDOC ## interface OptionC ### Description A codec representing Option that is able to deserialize the JSON representation of an Option. ### Signature export interface OptionC extends t.Type>, OptionOutput>, unknown> {} ``` -------------------------------- ### Create an option codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/option.ts.md Function to create an OptionC codec for a given inner codec. ```ts export function option(codec: C, name: string = `Option<${codec.name}>`): OptionC { ... } ``` -------------------------------- ### fromNullable Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromNullable.ts.md Creates a codec that replaces null or undefined inputs with a specified default value. ```APIDOC ## fromNullable ### Description Returns a clone of the given codec that replaces a nullable input (null or undefined) with the given value `a`. ### Method Not applicable (this is a function that returns a codec). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript 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) // Example usage: // T.decode(1) would result in right(1) // T.decode(null) would result in right(-1) // T.decode(undefined) would result in right(-1) // T.decode('a') would result in an error report ``` ### Response #### Success Response (200) This function returns a codec. The success response depends on the codec it wraps and the default value provided. #### Response Example ```json { "example": "The decoded value, or the default value if the input was null or undefined." } ``` ### Error Handling If the input cannot be decoded by the original codec and is not null or undefined, an error will be reported. ```ts // Example of error reporting: // PathReporter.report(T.decode('a')) would result in ['Invalid value "a" supplied to : fromNullable(number)'] ``` ``` -------------------------------- ### withFallback Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withFallback.ts.md Creates a codec that always succeeds by using a provided fallback value when the original codec fails. ```APIDOC ## withFallback ### Description Returns a clone of the given codec that always succeed using the given value `a` if the original codec fails. ### Method Function (not an HTTP method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```ts 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)) ``` ### Response #### Success Response (200) N/A (This is a function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Clone a codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/clone.ts.md Returns a clone of the provided io-ts codec. Requires importing the clone function from io-ts-types/lib/clone. ```ts export function clone(t: C): C { ... } ``` ```ts import { clone } from 'io-ts-types/lib/clone' import * as t from 'io-ts' assert.deepStrictEqual(clone(t.string), t.string) ``` -------------------------------- ### Create a Codec with Fallback Value Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withFallback.ts.md Use withFallback to create a codec that uses a provided default value if the original codec fails decoding. This is useful for ensuring a successful decode with a predictable outcome. ```typescript 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)) ``` -------------------------------- ### Create Map codecs with mapFromEntries Source: https://context7.com/gcanti/io-ts-types/llms.txt Converts arrays of key-value tuples into Map collections. Useful for JSON serialization of Map structures. ```typescript import { mapFromEntries } from 'io-ts-types/lib/mapFromEntries' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight } from 'fp-ts/lib/Either' import { ordString } from 'fp-ts/lib/Ord' import * as t from 'io-ts' // Create codec for Map const StringNumberMap = mapFromEntries(t.string, ordString, t.number) // Decode from array of tuples const result1 = StringNumberMap.decode([ ['a', 1], ['b', 2], ['c', 3] ]) if (isRight(result1)) { console.log(result1.right.get('b')) // 2 console.log(result1.right.size) // 3 } // Rejects duplicate keys const result2 = StringNumberMap.decode([ ['a', 1], ['a', 2] // duplicate key ]) console.log(PathReporter.report(result2)) // ['Invalid value [["a",1],["a",2]] supplied to : Map'] // Encoding back to array of tuples if (isRight(result1)) { const encoded = StringNumberMap.encode(result1.right) console.log(encoded) // [['a', 1], ['b', 2], ['c', 3]] } // Use for lookup tables const PriceList = t.type({ currency: t.string, prices: mapFromEntries(t.string, ordString, t.number) }) const priceData = { currency: 'USD', prices: [['apple', 1.5], ['banana', 0.75], ['orange', 2.0]] } ``` -------------------------------- ### withFallback Source: https://context7.com/gcanti/io-ts-types/llms.txt Creates a codec that uses a fallback value upon decoding failure, ensuring the codec always succeeds. ```APIDOC ## withFallback ### Description Returns a modified codec that uses a fallback value when decoding fails, instead of returning an error. The codec always succeeds. ### Method N/A (This is a function that returns a Codec) ### Endpoint N/A ### Parameters - **codec** (t.Codec) - Required - The base codec to enhance. - **fallbackValue** (A) - Required - The value to return if decoding fails. ### Request Example ```typescript import { withFallback } from 'io-ts-types/lib/withFallback' import * as t from 'io-ts' const NumberWithFallback = withFallback(t.number, -1) const result = NumberWithFallback.decode('not a number') // result will be: right(-1) const ConfigCodec = t.type({ port: withFallback(t.number, 3000), host: withFallback(t.string, 'localhost') }) const config = ConfigCodec.decode({ port: 'invalid' }) // config will be: right({ port: 3000, host: 'localhost' }) ``` ### Response #### Success Response (200) - **value** (A) - The decoded value, or the fallback value if decoding failed. #### Response Example ```json { "value": 42 } ``` #### Failure Response (e.g., 400) N/A - This codec always succeeds, returning the fallback value on error. ``` -------------------------------- ### Validate strings with NonEmptyString Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/NonEmptyString.ts.md Demonstrates decoding valid and invalid strings using the NonEmptyString codec. ```typescript import { NonEmptyString } from 'io-ts-types/lib/NonEmptyString' import { right } from 'fp-ts/lib/Either' import { PathReporter } from 'io-ts/lib/PathReporter' assert.deepStrictEqual(NonEmptyString.decode('a'), right('a')) assert.deepStrictEqual(PathReporter.report(NonEmptyString.decode('')), [ 'Invalid value "" supplied to : NonEmptyString' ]) ``` -------------------------------- ### optionFromNullable Function Signature Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/optionFromNullable.ts.md Creates a codec that wraps another codec, converting its output to an Option type. Handles null or undefined inputs by returning `None`, and valid outputs by returning `Some`. An optional name can be provided for the codec. ```typescript export function optionFromNullable( codec: C, name: string = `Option<${codec.name}>` ): OptionFromNullableC { ... } ``` -------------------------------- ### optionFromNullable Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/optionFromNullable.ts.md Creates a codec that converts a codec of a nullable type into an Option codec. ```APIDOC ## optionFromNullable ### Description Creates a codec that converts a codec of a nullable type into an Option codec. If the input is null or undefined, it returns `None`. Otherwise, it returns `Some` with the decoded value. ### Signature ```typescript export function optionFromNullable(codec: C, name?: string): OptionFromNullableC ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Not applicable for this function signature" } ``` ### Response #### Success Response (200) - **OptionFromNullableC** (interface) - The resulting codec that decodes to an Option type. #### Response Example ```json { "example": "Not applicable for this function signature" } ``` ``` -------------------------------- ### Create Either Codec Source: https://context7.com/gcanti/io-ts-types/llms.txt Use the `either` codec factory to create a codec for fp-ts Either types. It handles both Left and Right variants and validates inner types. ```typescript import { either } from 'io-ts-types/lib/either' import { left, right } from 'fp-ts/lib/Either' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight as isRightEither } from 'fp-ts/lib/Either' import * as t from 'io-ts' // Create Either codec const EitherStringNumber = either(t.string, t.number) // Decode Right value const result1 = EitherStringNumber.decode({ _tag: 'Right', right: 42 }) // result1 = right(right(42)) // Decode Left value const result2 = EitherStringNumber.decode({ _tag: 'Left', left: 'error message' }) // result2 = right(left('error message')) // Validates inner types const result3 = EitherStringNumber.decode({ _tag: 'Right', right: 'not a number' }) console.log(PathReporter.report(result3)) // ['Invalid value "not a number" supplied to : Either/1: Right/right: number'] // Encoding console.log(EitherStringNumber.encode(right(42))) // { _tag: 'Right', right: 42 } console.log(EitherStringNumber.encode(left('error'))) // { _tag: 'Left', left: 'error' } // Use for API results const ApiResult = either( t.type({ code: t.number, message: t.string }), // Error type t.type({ data: t.array(t.string) }) // Success type ) ``` -------------------------------- ### Create Codec from Refinement - io-ts-types Source: https://context7.com/gcanti/io-ts-types/llms.txt Use `fromRefinement` to create a codec from a type guard function. The codec validates input using the provided type guard and passes valid values through unchanged. This is useful for enforcing specific properties or types beyond basic io-ts primitives. ```typescript import { fromRefinement } from 'io-ts-types/lib/fromRefinement' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight } from 'fp-ts/lib/Either' // Create codec from type guard const isEven = (n: unknown): n is number => typeof n === 'number' && n % 2 === 0 const EvenNumber = fromRefinement('EvenNumber', isEven) const result1 = EvenNumber.decode(4) // result1 = right(4) const result2 = EvenNumber.decode(3) console.log(PathReporter.report(result2)) // ['Invalid value 3 supplied to : EvenNumber'] // Create codec for specific object shape interface Point { x: number; y: number } const isPoint = (u: unknown): u is Point => typeof u === 'object' && u !== null && 'x' in u && typeof (u as any).x === 'number' && 'y' in u && typeof (u as any).y === 'number' const PointCodec = fromRefinement('Point', isPoint) const result3 = PointCodec.decode({ x: 1, y: 2 }) // result3 = right({ x: 1, y: 2 }) ``` -------------------------------- ### Using withValidate to transform decoded values Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withValidate.ts.md Demonstrates wrapping a number codec to double the input value upon successful validation. ```ts import { withValidate } from 'io-ts-types/lib/withValidate' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import { either, right } from 'fp-ts/lib/Either' const T = withValidate(t.number, (u, c) => either.map(t.number.validate(u, c), n => n * 2)) assert.deepStrictEqual(T.decode(1), right(2)) assert.deepStrictEqual(PathReporter.report(T.decode(null)), ['Invalid value null supplied to : number']) ``` -------------------------------- ### Serialize fp-ts Option types with option codec Source: https://context7.com/gcanti/io-ts-types/llms.txt A codec factory for serializing and deserializing fp-ts Option types using their tagged union representation. ```typescript import { option } from 'io-ts-types/lib/option' import { none, some } from 'fp-ts/lib/Option' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight } from 'fp-ts/lib/Either' import * as t from 'io-ts' // Create an Option codec const OptionNumber = option(t.number) // Decode None const result1 = OptionNumber.decode({ _tag: 'None' }) // result1 = right(none) // Decode Some const result2 = OptionNumber.decode({ _tag: 'Some', value: 42 }) // result2 = right(some(42)) // Validates inner type const result3 = OptionNumber.decode({ _tag: 'Some', value: 'not a number' }) console.log(PathReporter.report(result3)) // ['Invalid value "not a number" supplied to : Option/1: Some/value: number'] // Encoding console.log(OptionNumber.encode(none)) // { _tag: 'None' } console.log(OptionNumber.encode(some(42))) // { _tag: 'Some', value: 42 } // Use in complex types const UserProfile = t.type({ name: t.string, nickname: option(t.string), age: option(t.number) }) const profile = UserProfile.decode({ name: 'John', nickname: { _tag: 'Some', value: 'Johnny' }, age: { _tag: 'None' } }) ``` -------------------------------- ### Create Set codecs with setFromArray Source: https://context7.com/gcanti/io-ts-types/llms.txt Converts arrays to Set collections. Requires an Ord instance and fails if duplicate elements are present. ```typescript import { setFromArray } from 'io-ts-types/lib/setFromArray' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight } from 'fp-ts/lib/Either' import { ordString, ordNumber } from 'fp-ts/lib/Ord' import * as t from 'io-ts' // Create codec for Set const StringSet = setFromArray(t.string, ordString) // Accepts arrays with unique elements const result1 = StringSet.decode(['a', 'b', 'c']) if (isRight(result1)) { console.log(result1.right) // Set { 'a', 'b', 'c' } console.log(result1.right.has('b')) // true } // Rejects arrays with duplicates const result2 = StringSet.decode(['a', 'b', 'a']) console.log(PathReporter.report(result2)) // ['Invalid value ["a","b","a"] supplied to : Set'] // Create codec for Set const NumberSet = setFromArray(t.number, ordNumber) const result3 = NumberSet.decode([1, 2, 3]) if (isRight(result3)) { console.log(NumberSet.encode(result3.right)) // [1, 2, 3] } // Use for unique constraints const TaggedItem = t.type({ id: t.number, tags: setFromArray(t.string, ordString) }) ``` -------------------------------- ### withMessage Utility Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withMessage.ts.md The withMessage function returns a clone of a given codec that uses a custom error message generator when validation fails. ```APIDOC ## withMessage ### Description Returns a clone of the given codec that sets the given string as the error message when validation fails. ### Signature `export function withMessage(codec: C, message: (i: t.InputOf, c: t.Context) => string): C` ### Parameters - **codec** (t.Any) - Required - The base codec to clone. - **message** ((i: t.InputOf, c: t.Context) => string) - Required - A function that returns a string to be used as the error message. ### Example ```ts import { withMessage } from 'io-ts-types/lib/withMessage' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import { right } from 'fp-ts/lib/Either' const T = withMessage(t.number, () => 'Invalid number') assert.deepStrictEqual(T.decode(1), right(1)) assert.deepStrictEqual(PathReporter.report(T.decode(null)), ['Invalid number']) ``` ``` -------------------------------- ### Validate UUIDs with UUID codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/UUID.ts.md Demonstrates decoding valid and invalid UUID strings using the UUID codec. ```typescript import { UUID } from 'io-ts-types/lib/UUID' import { right } from 'fp-ts/lib/Either' import { PathReporter } from 'io-ts/lib/PathReporter' assert.deepStrictEqual( UUID.decode('00000000-0000-0000-0000-000000000000'), right('00000000-0000-0000-0000-000000000000') ) assert.deepStrictEqual(PathReporter.report(UUID.decode('not a uuid')), [ 'Invalid value "not a uuid" supplied to : UUID' ]) ``` -------------------------------- ### Create Codec from Newtype Definition Source: https://context7.com/gcanti/io-ts-types/llms.txt Use `fromNewtype` to create a codec for a newtype-ts newtype. It handles automatic wrapping and unwrapping during encoding and decoding. Ensure the underlying type codec is provided. ```typescript import { fromNewtype } from 'io-ts-types/lib/fromNewtype' import { PathReporter } from 'io-ts/lib/PathReporter' import { isRight } from 'fp-ts/lib/Either' import { Newtype, iso } from 'newtype-ts' import * as t from 'io-ts' // Define a newtype for user IDs interface UserId extends Newtype<{ readonly UserId: unique symbol }, string> {} const userIdIso = iso() const UserIdCodec = fromNewtype(t.string) // Decode creates wrapped value const result1 = UserIdCodec.decode('user-123') if (isRight(result1)) { const userId: UserId = result1.right console.log(userIdIso.unwrap(userId)) // 'user-123' } // Validates underlying type const result2 = UserIdCodec.decode(123) console.log(PathReporter.report(result2)) // ['Invalid value 123 supplied to : fromNewtype(string)'] // Encoding unwraps the value const userId = userIdIso.wrap('user-456') console.log(UserIdCodec.encode(userId)) // 'user-456' // Define newtype with number interface PositiveInt extends Newtype<{ readonly PositiveInt: unique symbol }, number> {} const PositiveIntCodec = fromNewtype(t.number) // Use in domain types const User = t.type({ id: UserIdCodec, name: t.string }) ``` -------------------------------- ### withEncode Function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/withEncode.ts.md Creates a new codec based on an existing one, but uses a custom function to transform the encoded output. ```APIDOC ## withEncode ### Description Returns a clone of the given codec which uses the provided `encode` function to transform the output. ### Signature ```ts export function withEncode( codec: t.Type, encode: (a: A) => P, name: string = codec.name ): t.Type ``` ### Parameters - **codec** (t.Type) - Required - The base codec to clone. - **encode** ((a: A) => P) - Required - The function used to transform the encoded value. - **name** (string) - Optional - The name of the new codec (defaults to the base codec's name). ### Example ```ts import { withEncode } from 'io-ts-types/lib/withEncode' import * as t from 'io-ts' const T = withEncode(t.number, String) // T.decode(1) returns right(1) // T.encode(1) returns '1' ``` ``` -------------------------------- ### either function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/either.ts.md Creates a codec representing Either that can deserialize JSON representations of an Either. ```APIDOC ## either ### Description Returns a codec representing Either given codecs for L and A, enabling deserialization of JSON representations of an Either. ### Parameters - **leftCodec** (t.Mixed) - Required - Codec representing the Left type. - **rightCodec** (t.Mixed) - Required - Codec representing the Right type. - **name** (string) - Optional - The name of the codec, defaults to "Either". ### Request Example ```ts import { either } from 'io-ts-types/lib/either' import * as t from 'io-ts' const T = either(t.string, t.number) ``` ### Response - **EitherC** - A codec instance representing the Either type. ``` -------------------------------- ### Create Ordered Readonly Map Codec Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/readonlyMapFromEntries.ts.md Use `readonlyMapFromEntries` to create a codec for a Readonly Map where keys are ordered. It requires key and value codecs, and an `Ord` instance for the key type. ```typescript export function readonlyMapFromEntries( keyCodec: K, KO: Ord>, valueCodec: V, name: string = `ReadonlyMap<${keyCodec.name}, ${valueCodec.name}>` ): ReadonlyMapFromEntriesC { ... } ``` -------------------------------- ### Implement setFromArray function Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/setFromArray.ts.md Creates a codec that validates an array and converts it into a Set using a provided Ord instance. ```ts export function setFromArray( codec: C, O: Ord>, name: string = `Set<${codec.name}>` ): SetFromArrayC { ... } ``` -------------------------------- ### withMessage Source: https://context7.com/gcanti/io-ts-types/llms.txt Applies a custom error message function to a codec, replacing default io-ts error reporting. ```APIDOC ## withMessage ### Description Returns a modified codec that uses a custom error message function when validation fails, replacing the default io-ts error messages. ### Method N/A (This is a function that returns a Codec) ### Endpoint N/A ### Parameters - **codec** (t.Codec) - Required - The base codec to enhance. - **messageFn** (function(input: unknown): string) - Required - A function that returns the custom error message. ### Request Example ```typescript import { withMessage } from 'io-ts-types/lib/withMessage' import { PathReporter } from 'io-ts/lib/PathReporter' import * as t from 'io-ts' const Age = withMessage(t.number, () => 'Age must be a valid number') const result = Age.decode('not a number') console.log(PathReporter.report(result)) // Output: ['Age must be a valid number'] const PositiveNumber = withMessage( t.number, (input) => `Expected positive number, got: ${JSON.stringify(input)}` ) const result2 = PositiveNumber.decode('abc') console.log(PathReporter.report(result2)) // Output: ['Expected positive number, got: "abc"'] ``` ### Response #### Success Response (200) - **value** (A) - The successfully decoded value. #### Response Example ```json { "value": 25 } ``` #### Error Response - **error** (string) - The custom error message generated by `messageFn`. #### Error Response Example ```json { "error": "Age must be a valid number" } ``` ``` -------------------------------- ### nonEmptyArray Constructor Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/nonEmptyArray.ts.md The nonEmptyArray function is a constructor for creating NonEmptyArray codecs. ```APIDOC ## nonEmptyArray Constructor ### Description Creates a codec that validates non-empty arrays. ### Signature ```typescript export function nonEmptyArray(codec: C, name?: string): NonEmptyArrayC ``` ### Parameters - **codec** (C): The codec for the elements of the array. - **name** (string, optional): The name for the codec. Defaults to `NonEmptyArray<${codec.name}>`. ``` -------------------------------- ### MapFromEntriesC Interface Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/mapFromEntries.ts.md The MapFromEntriesC interface represents a codec for a Map where keys and values are defined by provided codecs. ```APIDOC ## MapFromEntriesC (interface) ### Description Represents a codec for a Map. ### Signature ```typescript export interface MapFromEntriesC extends t.Type, t.TypeOf>, Array<[t.OutputOf, t.OutputOf]>, unknown> {} ``` ``` -------------------------------- ### fromNewtype function signature Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/fromNewtype.ts.md The type signature for the fromNewtype function. ```ts export function fromNewtype( codec: t.Type, t.OutputOf>>, name = `fromNewtype(${codec.name})` ): t.Type, unknown> { ... } ``` -------------------------------- ### either Function Signature Source: https://github.com/gcanti/io-ts-types/blob/master/docs/modules/either.ts.md Signature for the either codec factory function. ```ts export function either( leftCodec: L, rightCodec: R, name: string = `Either<${leftCodec.name}, ${rightCodec.name}>` ): EitherC { ... } ```