/** * Validate arrays * @return a function that parses arrays * @param parseItem */ export declare const array: (parseItem: Parser) => Parser; /** * Validate arrays * @param itemGuard validates every item in the array * @return a guard function that validates arrays */ export declare const arrayGuard: (itemGuard: Guard) => Guard; export declare const arrayGuardMemo: (itemGuard: Guard) => Guard; export declare const arrayMemo: (parseItem: Parser) => Parser; /** * Transform successful results into either success or failure. * This is useful for chaining parsers. * @example * After parsing an array of numbers, ensure it is non-empty: * ``` * const parseNonEmptyArray = chain(array(parseNumber), (value) => * value.length > 0 * ? success(value) * : failure('Expected non-empty array'), * ) * ``` * @param parser * @param parseSuccess */ export declare const chain: (parser: Parser, parseSuccess: (value: A) => ParseResult) => Parser; /** * Dictionaries are objects that map strings to other values. * * Due to how TypeScript works, this function has two behaviors at the type level, depending on `Key` (At runtime, it always behaves the same): * - When the key is `string`, it validates `Record`. When `noUncheckedIndexedAccess` is enabled, TypeScript understands that a value retrieved with a string the value can be `undefined`. However, the value is _not semantically identical_ to `Partial>`. * - When the key is a subset of `string`, it validates `Partial>`. If the properties were not marked as optional, TypeScript would assume that all keys map to values. * * @example * Validate a dictionary: * ```ts * const parseDictionary = dictionary(isString, isString) * parseDictionary({ hello: 'world' }) // -> Success * parseDictionary({ hello: 1 }) // -> Failure * ``` * @example * You can transform the keys and values; for example, to only allow lowercase strings: * ```ts * const parseLowerCase = (data: unknown): data is Lowercase => * typeof data === 'string' ? failure('Not a string') : success(data.toLowerCase()) * const parseDictionary = dictionary(parseLowerCase, parseLowerCase) * parseDictionary({ hello: 'world' }) // -> Success<{ hello: 'world' }> * parseDictionary({ Hello: 'world' }) // -> Success<{ hello: 'world' }> * parseDictionary({ hello: 'World' }) // -> Success<{ hello: 'world' }> * ``` * @param parseKey parses every key * @param parseValue parses every value * @returns a parser for a record */ export declare const dictionary: (parseKey: Parser, parseValue: Parser) => Parser : Partial>>; /** * Dictionaries are objects that map strings to other values. * * * Due to how TypeScript works, this function has two behaviors at the type level, depending on `Key` (At runtime, it always behaves the same): * - When the key is `string`, it validates `Record`. When `noUncheckedIndexedAccess` is enabled, TypeScript understands that a value retrieved with a string the value can be `undefined`. However, the value is _not semantically identical_ to `Partial>`. * - When the key is a subset of `string`, it validates `Partial>`. If the properties were not marked as optional, TypeScript would assume that all keys map to values. * * @example * Validate a dictionary: * ```ts * const isDictionary = dictionaryGuard(isString, isString) * isDictionary({ hello: 'world' }) // -> true * ``` * @example * You can limit the set of keys; for example, to only allow lowercase strings: * ```ts * const isLowerCase = (data: unknown): data is Lowercase => * typeof data === 'string' && data === data.toLowerCase() * const isDictionary = dictionaryGuard(isLowerCase, isString) * isDictionary({ hello: 'world' }) // -> true * isDictionary({ Hello: 'world' }) // -> false * ``` * @param keyGard validates every key * @param valueGuard validates every value * @returns a guard for a dictionary */ export declare const dictionaryGuard: (keyGard: Guard, valueGuard: Guard) => Guard : Partial>>; export declare const dictionaryGuardMemo: (keyGard: Guard, valueGuard: Guard) => Guard : Partial>>; export declare const dictionaryMemo: (parseKey: Parser, parseValue: Parser) => Parser : Partial>>; /** * Compares the input against a primitive values with the strict equality operator (`===`). * The inferred type of the parser is that of a literal type; for example, `equals('red')` returns a `Parser<'red'>`. * @example * ```ts * const parseInfo = equals('info') * parseInfo('info') // => ParseSuccess<'info'> * parseInfo('error') // => ParseFailure * * const parseOne = equals(1) * parseOne(1) // => ParseSuccess<1> * parseOne(2) // => ParseFailure * ``` * @example * Commonly used in discriminated unions: * ```ts * const parseResult = oneOf([ * object({ * tag: equals('success') * }), * object({ * tag: equals('error') * }), * ]) * ``` * @param constant One or more primitive values that are compared against `data` with the `===` operator. * @returns A parser function that validates the input against the provided constants. */ export declare const equals: (constant: T) => Parser; /** * Compares the input against a list of primitive values with the strict equality operator (`===`). * The inferred type of the guard is that of a literal type; for example, `equalsGuard('red')` returns a `Guard<'red'>`. * @example * ```ts * const isRed = equalsGuard('red') * isRed('red') // -> true * isRed('blue') // -> false * * const isOne = equalsGuard(1) * isOne(1) // -> true * isOne(2) // -> false * ``` * @example * Commonly used in discriminated unions: * ```ts * const isResult = oneOfGuard([ * objectGuard({ * tag: equalsGuard('success') * }), * objectGuard({ * tag: equalsGuard('error') * }), * ]) * ``` * @param constant compared against `data` with the `===` operator. */ export declare const equalsGuard: (constant: T) => Guard; /** * Describes why and where parsing failed. */ export declare type Failure = { /** * A human-readable description of why parsing failed. Intended for logging and debugging — do not pattern-match on this string, as its exact wording may change between releases. */ message: string; /** * The location in the data structure where parsing failed, as a sequence of path segments from the root. Use {@link formatPath} to format it as a JSONPath string. */ path: PathSegment[]; }; /** * Create a failure parsing result. * @example * ```ts * const customParser: Parser = (data) => { * if (typeof data === 'number') { * return success(data) * } * return failure('Expected a number') * } * ``` * @param message */ export declare const failure: (message: string) => ParseFailure; /** * Formats a failure `Path` to a JsonPath. * @example * ```ts * const path = [{ tag: 'object', key: 'name' }] * console.log(formatPath(path)) * // "$.name" * ``` * @param path */ export declare const formatPath: (path: PathSegment[]) => string; /** * Formats a failure to a human-readable string. * This is useful for debugging and logging parse results. * It formats both successful and unsuccessful parse results. * - Successful results are formatted as `ParseSuccess: `, where `` comes from `Object.prototype.toString()`. To customize the output, you can pass a `toString` function that converts the value to a string. * - Failures include the error message and the path where the failure occurred. * @example * Format an unsuccessful parse result: * ```ts * const parseUser = object({ name: parseString }) * const res = parseUser({ name: 123 }) * console.log(formatResult(res)) // -> "ParseFailure: Expected value to be of type string at $.name" * ``` * @example * Format a successful parse result: * ```ts * const parseUser = object({ name: parseString }) * const res = parseUser({ name: 'Alice' }) * console.log(formatResult(res, JSON.stringify)) // -> "ParseSuccess: {"name":"Alice"}" * ``` * @param result The result of a parse operation. * @param formatValue Optional function to convert the value to a string. If not provided, it uses string interpolation. */ export declare const formatResult: (result: ParseResult, formatValue?: (value: T) => string) => string; /** * A function that returns a [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates) on the argument. */ export declare type Guard = (data: unknown) => data is T; /** * A parser that always succeeds */ export declare type InfallibleParser = (data: unknown) => ParseSuccess; /** * Extract the type from a parser or guards * - In parsers, extract the type in the type parameter. * - In guards, extract the type in the [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates). * @example * type User = Infer * @example * type User = Infer * @limitations Optional `unknown` properties will be inferred as required. At runtime, the property _is_ optional: only the inferred type has a discrepancy. For most use cases, this is not a problem. If you are adamant on being correct, consider declaring the type instead of inferring it (see the following section). This edge case is a small compromise between ease-of-use and type correctness. * @typeParam T — a parser or guard */ export declare type Infer | Parser> = T extends UnsuccessfulParser ? never : T extends Parser ? R : T extends Guard ? R : never; /** * Returns a parser that checks whether the data is an instance of the given constructor. * @example * ```ts * const parseError = instanceOf(Error) * parseError(new Error()) // -> Success * ``` * @param constructor the right-hand side argument of the `instanceof` operator */ export declare const instanceOf: (constructor: { new (...args: never[]): T; }) => Parser; /** * Returns a guard that checks whether the data is an instance of the given constructor. * @example * ```ts * const isError = instanceOfGuard(Error) * isError(new Error()) // -> true * ``` * @param constructor the right-hand side argument of the `instanceof` operator */ export declare const instanceOfGuard: (constructor: { new (...args: never[]): T; }) => Guard; export declare const isArray: (data: unknown) => data is unknown[]; export declare const isBigInt: (data: unknown) => data is bigint; export declare const isBoolean: (data: unknown) => data is boolean; /** * Check if the result is a failure * @param result */ export declare const isFailure: (result: ParseResult) => result is ParseFailure; export declare const isFunction: (data: unknown) => data is Function; /** * Checks if the given data is a valid JSON value. * Only plain JSON values are allowed. For example, `Date`, `Map`, `Set`, and custom class instances are not valid JSON values. * @param data */ export declare const isJsonValue: Guard; /** * Returns `false` for any input. * @param data */ export declare const isNever: (data: unknown) => data is never; /** * Use this when the data that you want to guard is already a known array * @param data an array * @return `true` if data has at least one element */ export declare const isNonEmptyArray: (data: T[]) => data is [T, ...T[]]; export declare const isNull: (data: unknown) => data is null; export declare const isNumber: (data: unknown) => data is number; export declare const isObject: (data: unknown) => data is object; export declare const isString: (data: unknown) => data is string; /** * Check if the result is a success * @param result */ export declare const isSuccess: (result: ParseResult) => result is ParseSuccess; export declare const isSymbol: (data: unknown) => data is symbol; export declare const isUndefined: (data: unknown) => data is undefined; /** * Returns `true` for any input. Use to skip validation. * @param data */ export declare const isUnknown: (data: unknown) => data is unknown; /** * A value that can be encoded as JSON. * @example * ```ts * const value: JsonValue = { * name: 'John', * age: 30, * isActive: true, * hobbies: ['reading', 'gaming'], * address: { * street: '123 Main St', * city: 'Anytown', * zip: '12345', * }, * metadata: null, * } * ``` */ export declare type JsonValue = null | boolean | number | string | { [x: string]: JsonValue; } | JsonValue[]; /** * Creates a lazy-loaded function that initializes the function only when it is called for the first time. * With `lazy`, you can create recursive parsers without running into circular dependencies. * Also useful to lazily initialize just-in-time compiled parsers and guards. * @example * Create recursive parsers with `lazy`. * Note that you must use explicit type annotations: * ```ts * import { lazy, type Parser, object, parseString, optional } from 'pure-parse' * * type Person = { * name: string * father?: Person * mother?: Person * } * const parsePerson: Parser = lazy(() => * object({ * name: parseString, * father: optional(parsePerson), * mother: optional(parsePerson), * }), * ) * ``` * @param constructFn */ export declare const lazy: unknown>(constructFn: () => T) => T; /** * Transform the values of successful results. * @example * Transform strings to uppercase * ```ts * const parseToUpperCase = map(parseString, (str) => str.toUpperCase()) * parseToUpperCase('hello') // -> ParseSuccess<'HELLO'> * parseToUpperCase(123) // -> ParseFailure * ``` * @param parser * @param mapSuccess */ export declare const map: (parser: Parser, mapSuccess: (value: A) => B) => Parser; /** * Memoizes a validator function—a parser or a guard. * Internally, a memoized function uses a [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) to prevent memory leaks. * While you can wrap any validator function within `memo`, primitive values will not be memoized. * @example * const parseUser = memo(object({ * id: parseNumber, * name: parseString, * })) * @example * It can be used to for nested properties * ```ts * const parseUser = object({ * id: parseNumber, * name: parseString, * address: memo(object({ * street: parseString, * city: parseString, * })), * }) * ``` * @param validator A parser or guard function. * @returns A memoized version of `validator`. */ export declare const memo: unknown>(validator: T) => T; /** * Given a higher order function that constructs a validator, returns a new function that also constructs a validator, but the validator will be memoized. * @example * const objectMemo = memo2(object) * const parseUser = objectMemo({ * id: parseNumber, * name: parseString, * }) * @param validatorConstructor A higher order function that takes a schema and constructs a validator—a parser or a guard. * @returns A function of the same type of `validatorConstructor`, but when called, the returned function is memoized. */ export declare const memoizeValidatorConstructor: Parser | Guard>(validatorConstructor: T) => T; /** * Validate non-empty arrays * @param itemGuard validates every item in the array * @return a guard function that validates non-empty arrays */ export declare const nonEmptyArrayGuard: (itemGuard: Guard) => Guard<[T, ...T[]]>; export declare const nonEmptyArrayGuardMemo: (itemGuard: Guard) => Guard<[T, ...T[]]>; /** * Represents a value that can be `null`. Shorthand for `oneOf(parseNull, parser)`. * @example * const parseNullableString = nullable(parseString) * parseNullableString(null) // => ParseSuccess * parseNullableString('abc') // => ParseSuccess * @param parser a parser function. */ export declare const nullable: (parser: Parser) => Parser; /** * Create a union with `null`. Convenient when creating nullable properties in objects. Alias for `unionGuard(isNull, guard)`. * @param guard */ export declare const nullableGuard: (guard: Guard) => (data: unknown) => data is T | null; /** * Objects have a fixed set of properties of different types. * If the `data` received has properties that are not declared in the parser, * the extra properties are omitted from the result. * @see {@link objectStrict} for a strict version. * @example * Object with both required and optional properties: * ```ts * const parseUser = object({ * id: parseNumber, * active: parseBoolean, * name: parseString, * email: optional(parseString), * }) * ``` * @example * Annotate explicitly: * ```ts * type User = { * id: number * name?: string * } * * const parseUser = object({ * id: parseNumber, * name: optional(parseString), * }) * ``` * @limitations Optional `unknown` properties will be inferred as required. * See {@link Infer} > limitations for in-depth information. * @param schema maps keys to validation functions. * @return a parser function that validates objects according to `schema`. */ export declare const object: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; /** * Same as {@link object}, but performs just-in-time (JIT) compilation with the `Function` constructor, which greatly increases the execution speed of the validation. * However, the JIT compilation is slow and gets executed at the time when the validation function is constructed. * When invoking this function at the module level, it is recommended to wrap it in {@link lazy} to defer the JIT compilation to when the validation function is called for the first time. * This function will be blocked in environments where the `Function` constructor is blocked; for example, when the [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) policy is set without the `'unsafe-eval`' directive. * @see {@link object} for a non-compiled version of this function. * @see {@link lazy} for deferring the JIT compilation. * @see {@link objectStrictCompiled} for a strict version. * @example * Defer the JIT compilation to when the validation function is called for the first time. * ```ts * const isUser = lazy(() => objectCompiled({ * id: isNumber, * name: isString, * }) * ``` * @see {@link object} for a non-just-in-time compiled version of this function. * @param schema maps keys to validation functions. */ export declare const objectCompiled: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; export declare const objectCompiledMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; /** * Objects have a fixed set of properties of different types. * @example * ```ts * Object with both required and optional properties: * const isUser = objectGuard({ * id: isNumber, * uid: isString, * active: isBoolean, * email: optional(isString), * }) * ``` * Note that optional properties will be inferred as required properties that can be assigned `undefined`. See {@link Infer} > limitations for in-depth information. * @example * Annotate explicitly: * ```ts * type User = { * id: number * name: string * } * * const isUser = object({ * id: isNumber, * name: isString, * }) * ``` * @see {@link objectGuardCompiled} for just-in-time compiled version of this function. * @param schema maps keys to validation functions. */ export declare const objectGuard: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalGuard : Guard; }) => Guard extends undefined ? T : WithOptionalFields>; /** * Same as {@link objectGuard}, but performs just-in-time (JIT) compilation with the `Function` constructor, which greatly increases the execution speed of the validation. * However, the JIT compilation is slow and gets executed at the time when the validation function is constructed. * When using this function at the module level, it is recommended to wrap it in {@link lazy} to defer the JIT compilation to when the validation function is called for the first time. * This function will be blocked in environments where the `Function` constructor is blocked; for example, when the [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) policy is set without the `'unsafe-eval`' directive. * @example * Defer the JIT compilation to when the validation function is called for the first time. * ```ts * const isUser = lazy(() => objectGuardCompiled({ * id: isNumber, * name: isString, * }) * ``` * @see {@link objectGuard} for a non-just-in-time compiled version of this function. * @param schema maps keys to validation functions. */ export declare const objectGuardCompiled: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalGuard : Guard; }) => Guard extends undefined ? T : WithOptionalFields>; export declare const objectGuardCompiledMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalGuard : Guard; }) => Guard extends undefined ? T : WithOptionalFields>; export declare const objectGuardMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalGuard : Guard; }) => Guard extends undefined ? T : WithOptionalFields>; export declare const objectMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; /** * Like `object`, but fails when the input `data` object has undeclared properties. * Although `object` removes undeclared properties from the result, * there are scenarios where you want to reject the input if it has extra properties. * @see {@link object} for a non-strict version. * @example * When designing APIs, you want to reject calls to the API that includes undeclared properties, * as this will allow you to add new properties in the future without breaking changes. * * For example, consider a REST API endpoint `PUT /user/:id`, which is validating the body with the non-strict object parser: * ```ts * const handlePutUser = (body: unknown) => { * const parseBody = object({ * id: parseNumber, * name: parseString, * }) * } * ``` * A client decides to call it with an extra property `email`: * ```ts * fetch('/user/1', { * method: 'PUT', * body: JSON.stringify({ * id: 123, * name: 'Alice', * email: null * }), * ``` * Since `handlePutUser` does not reject the API call, the client's success will succeed. * * Now, the backend is updated to include the email property: * ```ts * const handlePutUser = (body: unknown) => { * const parseBody = object({ * id: parseNumber, * name: parseString, * email: optional(parseString), * }) * } * ``` * That is, `email` is optional, but not nullable. * If the client now sends the same request, it will suddenly fail. * * To avoid such breaking change, use `objectStrict`: * ```ts * const handlePutUser = (body: unknown) => { * const parseBody = objectStrict({ * id: parseNumber, * name: parseString, * }) * } * ``` * @param schema */ export declare const objectStrict: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; /** * Like `objectCompiled`, but fails when the input `data` object has undeclared properties in the same manner as `objectStrict`. * @see {@link objectStrict} for a non-compiled version. * @see {@link objectCompiled} for a non-strict version. * @param schema */ export declare const objectStrictCompiled: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; export declare const objectStrictCompiledMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; export declare const objectStrictMemo: >(schema: { [K in keyof T]-?: {} extends Pick ? OptionalParser : Parser; }) => Parser extends undefined ? T : WithOptionalFields>; declare type OmitProperty = typeof omitProperty; /** * Returned from optional parsers to indicate that a property should be omitted */ declare const omitProperty: unique symbol; /** * Executes `parsers` in order and returns the first successful parsing attempt, or a failure if all fail. * Use it to parse unions, to parse data that comes in different shape, and to provide fallbacks for failed parsing attempts. * @see {@link withDefault} for a shorthand for fallback with a static value. * @example * Parse unions: * ```ts * const parseNumberOrString = oneOf(parseNumber, parseString) * parseNumberOrString(0) // => ParseSuccess * parseNumberOrString('abc') // => ParseSuccess * parseNumberOrString(null) // => ParseError * ``` * @example * Parse discriminated unions: * ```ts * const parseResult = oneOf( * object({ * tag: equals('success') * value: parseString * }), * object({ * tag: equals('error') * }), * ) * ``` * @example * Provide fallbacks for failed parsing attempts; for example, parse a number from data that is either a number or a stringified number: * ```ts * const parseStrOrNum = fallback([parseNumber, parseNumberFromString]) * parseStrOrNum(2) // -> { tag: 'success', value: 2 } * parseStrOrNum('2') // -> { tag: 'success', value: 2 } * ``` * (Do not encode data like this when there's a choice; but sometimes, existing data comes in weird shapes and forms.) * @example * Provide a static default value when parsing fails: * ```ts * const parseName = oneOf([ * parseString, * () => success('Anonymous') * ]) * ``` * You can also use {@link withDefault} for this use case. * @example * When explicitly annotating `oneOf`, provide a tuple as type argument: * ```ts * type Success = { * tag: 'success' * value: string * } * type Failure = { * tag: 'failure' * } * type Result = Success | Failure * const parseLogLevel = equals<[Success, Failure]>( * object({ * tag: equals('success') * value: parseString * }), * object({ * tag: equals('error') * }), * ) * ``` * Due to a limitation of TypeScript, it is not possible to write `oneOf()`. Therefore, it is generally recommended to omit the type arguments for oneOf and let TypeScript infer them. * @param parsers A list of parsers to be called in order. * @return A parser function that will call the parsers in `parsers` in order and return the result of the first successful parsing attempt, or a failure if all parsing attempts fail. */ export declare const oneOf: (...parsers: { [K in keyof T]: Parser; }) => Parser; /** * Executes `guards` in order and returns true if any guard matches. The result type is a union. * @example * Commonly used in discriminated unions: * ```ts * const isResult = oneOfGuard([ * objectGuard({ * tag: equalsGuard('success') * }), * objectGuard({ * tag: equalsGuard('error') * }), * ]) * ``` * @example * When explicitly annotating `oneOfGuard`, provide a tuple of the union members as type argument: * ```ts * const isId = oneOfGuard<[string, number]>(isString, isNumber) * ``` * Due to a limitation of TypeScript, it is not possible to write `unionGuard()` or `equalsGuard<'red' | 'green' | 'blue'>()`. Therefore, it is generally recommended to omit the type arguments for union types and let TypeScript infer them. * @param guards any of these guard functions must match the data. * @return a guard function that validates unions */ export declare const oneOfGuard: (...guards: { [K in keyof T]: Guard; }) => (data: unknown) => data is T[number]; /** * Represent an optional property in an object. It is supposed to be used in combination with `object`. * Note that in TypeScript, optional properties may be assigned `undefined` or omitted entirely from the object. * This function is special because it is used internally by `object` to differentiate between optional properties from required properties that can be `undefined`. * Only use this in objects: it _can_ return the {@link OmitProperty} symbol to indicate that the property was omitted from the object. * @example * Wrap properties in `optional` to make them optional: * ```ts * type User = { * id: number * email?: string * } * const parseUser = object({ * id: parseNumber, * email: optional(parseString), * }) * parseUser({ id: 123 }) // -> ParseSuccess * parseUser({ id: 123, email: undefined }) // -> ParseSuccess * parseUser({ id: 123, email: 'abc@test.com' }) // -> ParseSuccess * ``` * If `email` instead was defined as a union of `string` and `undefined`, the first call to `parseUser` would fail. * @param parser A parser to parse the property with. * @return a special parser that represents an optional value. If invoked directly, it behaves the same as `oneOf(parseUndefined, parser)`. If invoked by `object`, `object` will treat the property as optional. */ export declare const optional: (parser: Parser) => OptionalParser; /** * Special guard to check optional values */ export declare type OptionalGuard = (data: unknown) => data is T | undefined | OmitProperty; /** * Represent an optional property. Note that in TypeScript, optional properties may be assigned `undefined` or omitted entirely from the object. * @example * Wrap properties in `optional` to make them optional: * ```ts * type User = { * id: number * email?: string * } * const isUser = objectGuard({ * id: isNumber, * email: optionalGuard(isString), * }) * isUser({ id: 123 }) // -> true * isUser({ id: 123, email: undefined }) // -> true * isUser({ id: 123, email: 'abc@test.com' }) // -> true * ``` * @param guard */ export declare const optionalGuard: (guard: Guard) => OptionalGuard; declare type OptionalKeys = Values<{ [K in keyof T]: unknown extends T[K] ? never : OmitProperty extends T[K] ? K : never; }>; /** * Represents an optional property that can also be null. Shorthand for `optional(oneOf(parseNull, parser))`. * @param parser a parser function. */ export declare const optionalNullable: (parser: Parser) => OptionalParser; /** * Create an optional property that also can be `null`. Convenient when creating optional nullable properties in objects. Alias for `optional(oneOfGuard(isNull, guard))`. * @param guard */ export declare const optionalNullableGuard: (guard: Guard) => OptionalGuard; /** * Special parser to check optional values */ export declare type OptionalParser = (data: unknown) => ParseResult; /** * Parse `bigint` * @example * parseBigInt(0n) // => ParseSuccess * @example * parseBigInt(0) // => ParseFailure * @param data data to be validated */ export declare const parseBigInt: (data: unknown) => ParseSuccess | ParseFailure; /** * Parse `boolean` * @example * parseBoolean(true) // => ParseSuccess * @example * parseBoolean(false) // => ParseSuccess * @example * parseBoolean(0) // => ParseFailure * @param data data to be validated */ export declare const parseBoolean: (data: unknown) => ParseSuccess | ParseFailure; /** * The parsing failed. */ export declare type ParseFailure = { tag: 'failure'; error: Failure; }; /** * Parses a JSON value from a JSON string. * @example * ```ts * parseJson('{"key": "value"}') // -> ParseSuccess * parseJson('123') // -> ParseSuccess * ``` * The value must be a JSON-string: * ```ts * parseJson('not a json string') // -> ParseFailure * parseJson(123) // -> ParseFailure * parseJson(null) // -> ParseFailure * ``` * @example * You can chain together `parseJson` with other parsers: * ```ts * const parseUserJson = chain(parseJson, parseUser) * parseUserJson('{"name": "John", "age": 30}') // -> ParseSuccess<{ name: string, age: number }> * ``` * @param data */ export declare const parseJson: Parser; /** * A parser that always fails. * * `never` is the bottom type—the empty set of values—so no value can satisfy it. * It is the identity element for {@link oneOf}: unioning any parser with `parseNever` yields that parser unchanged, making it the natural base case when folding a list of parsers into a union. * Most users will never call it directly; it is primarily present in the library for completeness. * * @example * Always fails: * ```ts * parseNever(0) // => ParseFailure * parseNever('abc') // => ParseFailure * parseNever(null) // => ParseFailure * ``` * @param data data to be validated * @see {@link parseUnknown} for the opposite: a parser that always succeeds */ export declare const parseNever: UnsuccessfulParser; /** * Parse `null` * @example * parseNull(null) // => ParseSuccess * @example * parseNull(undefined) // => ParseFailure * @param data data to be validated */ export declare const parseNull: (data: unknown) => ParseSuccess | ParseFailure; /** * Parse `number` * @example * parseNumber(0) // => ParseSuccess * @example * parseNumber('0') // => ParseFailure * @param data data to be validated */ export declare const parseNumber: (data: unknown) => ParseSuccess | ParseFailure; /** * Parses a number from a stringified number. The result is always a `number`, and never `NaN` or `±Infinity`. * Strings that describe numbers (without any other characters involved) yield results. * Numbers that can be represented in binary, octal, decimal, hexadecimal, and scientific format are supported. * @param data */ export declare const parseNumberFromString: Parser; export declare type Parser = (data: unknown) => ParseResult; /** * Describes the result of a parsing operation. * The `tag` and `error` properties can be used to distinguish between success and failure. * @example * Use `error` to distinguish between success and failure: * ```ts * const result = parseNumber(data) * if(result.error) { * console.error(formatResult(result)) * return * } * console.log(result.value) * ``` * @example * Use `tag` to distinguish between success and failure: * ```ts * const result = parseNumber(data) * switch (result.tag) { * case 'failure': * console.error(formatResult(result)) * break * case 'success': * console.log(result.value) * break */ export declare type ParseResult = ParseSuccess | ParseFailure; /** * Construct a parser from a type guard. * Tip: construct parsers from scratch for better error messages, and generally more flexibility. * @example * ```ts * const isUser = objectGuard({ * id: isNumber, * name: isString, * }) * const parseUser = parserFromGuard(isUser) * ``` * @param guard */ export declare const parserFromGuard: (guard: Guard) => Parser; /** * Parse `string` * @example * parseString('abc') // => ParseSuccess * @example * parseString(0) // => ParseFailure * @param data data to be validated */ export declare const parseString: (data: unknown) => ParseSuccess | ParseFailure; /** * The data adheres to the schema. The `value` is equal to the parsed data */ export declare type ParseSuccess = { tag: 'success'; value: T; error?: never; }; /** * Parse `symbol` * @example * parseSymbol(Symbol('abc')) // => ParseSuccess * @example * parseSymbol('abc') // => ParseFailure * @param data data to be validated */ export declare const parseSymbol: (data: unknown) => ParseSuccess | ParseFailure; /** * Parse `undefined` * @example * parseUndefined(undefined) // => ParseSuccess * parseUndefined(null) // => ParseFailure * @param data data to be validated */ export declare const parseUndefined: (data: unknown) => ParseSuccess | ParseFailure; /** * A parser that always succeeds. * Parsing `unknown` always succeeds because all values can be assigned to `unknown`—`unknown` corresponds to the set of all values. * @see {@link parseNever} for a counterpart * @example * Use to skip validation, as it results in a success for any input. * ```ts * const parseResponse = object({ * status: parseNumber, * data: unknown, * }) * parseResponse({ * status: 200, * data: { id: 123, name: 'John' } * }) // => ParseSuccess<{ status: number, data: unknown }> * ``` * @param data data to be validated */ export declare const parseUnknown: InfallibleParser; /** * Describes the path in a data structure where parsing failed. */ export declare type PathSegment = { tag: 'object'; key: string; } | { tag: 'array'; index: number; }; /** * A JavaScript primitive */ export declare type Primitive = null | undefined | boolean | number | string | bigint | symbol; /** * Propagate a failure result in a nested structure. * When parsing objects and arrays with nested values, the failure at the root level should convey where in the hierarchy the failure occurred. * @param failureRes * @param pathSegment */ export declare const propagateFailure: (failureRes: ParseFailure, pathSegment: PathSegment) => ParseFailure; /** * Transform failed results into either success or failure. * This is useful for error handling. * @example * Fall back to a default value if parsing fails: * ``` * const parseCount = recover( * parseNumber, * () => 0 * ) * ``` * @param parser * @param parseFailure */ export declare const recover: (parser: Parser, parseFailure: (error: ParseFailure["error"]) => ParseResult) => Parser; export declare type RequiredGuard = (data: unknown) => data is Exclude; declare type RequiredKeys = Values<{ [K in keyof T]: unknown extends T[K] ? K : OmitProperty extends T[K] ? never : K; }>; /** * A parser that does not represent an optional property. */ export declare type RequiredParser = (data: unknown) => ParseResult>; /** * Takes a complex type expression and simplifies it to a plain object. Useful when inferring types. */ declare type Simplify = T extends infer _ ? { [K in keyof T]: T[K]; } : never; /** * Create a successful parsing result. * @example * ```ts * const customParser: Parser = (data) => { * if (typeof data === 'number') { * return success(data) * } * return failure('Expected a number') * } * @param value */ export declare const success: (value: T) => ParseSuccess; /** * Construct parsers for tuples. * If the `data` has more elements than expected, the extra elements are omitted from the result. * @example * Parse 2D coordinates: * ```ts * const parseVector2 = tuple([parseNumber, parseNumber]) * parseVector2([12.5, 45.0]) // -> ParseSuccess<[number, number]> * ``` * @example * Declare the type explicitly with type arguments: * ```ts * const parseVector2 = tuple<[number, number]>([parseNumber, parseNumber]) * parseVector2([12.5, 45.0]) // -> ParseSuccess<[number, number]> * ``` * @param parsers an array of parsers. Each parser validates the corresponding element in the data tuple. * @returns a parser that validates tuples. */ export declare const tuple: (parsers: [...{ [K in keyof T]: Parser; }]) => Parser; /** * @param guards an array of guards. Each guard validates the corresponding element in the data tuple. */ export declare const tupleGuard: (guards: [...{ [K in keyof T]: Guard; }]) => Guard; export declare const tupleGuardMemo: (guards: [...{ [K in keyof T]: Guard; }]) => Guard; export declare const tupleMemo: (parsers: [...{ [K in keyof T]: Parser; }]) => Parser; /** * Represents a value that can be `undefined`. Shorthand for `oneOf(parseUndefined, parser)`. * @example * const parseUndefineableString = undefineable(parseString) * parseUndefineableString(undefined) // => ParseSuccess * parseUndefineableString('abc') // => ParseSuccess * @param parser */ export declare const undefineable: (parser: Parser) => Parser; /** * Create a union with `undefined`, which is different from optional properties. Alias for `unionGuard(isUndefined, guard)`. * @param guard */ export declare const undefineableGuard: (guard: Guard) => (data: unknown) => data is T | undefined; export declare const unionGuardMemo: (...guards: { [K in keyof T]: Guard; }) => (data: unknown) => data is T[number]; export declare const unionMemo: (...parsers: { [K in keyof T]: Parser; }) => Parser; /** * A parser that always fails */ export declare type UnsuccessfulParser = (data: unknown) => ParseFailure; /** * Used to index an object. The benefit of this over `T[keyof T]` is that `T[keyof {}]` gives `undefined`, while `Values<{}>` gives `never`. */ declare type Values = keyof T extends never ? never : T[keyof T]; /** * Provide a default value to fall back to when parsing fails. * Since the default value is static, the parser will always succeed. * @see {@link oneOf} for a more flexible alternative. * @example * Parse a number with a default value: * ```ts * const parseNum = withDefault(parseNumber, 0) * parseNum(1) // -> ParseSuccess * parseNum(null) // -> ParseSuccess<0> * ``` * @example * Parse an array of objects, but replace the objects with a default value if the parsing fails: * ```ts * const parseContent = array( * withDefault( * object({ * tag: equals('text'), * value: parseString, * }), * { * tag: 'unknown', * }, * ), * ) * * const res = parseContent([{ * tag: 'text', * value: 'hello' * }, { * tag: 'number' * value: 123 * }]) * ``` * where res becomes: * ```ts * [ * { tag: 'text', value: 'hello'}, * { tag: 'unknown' } * ] * ``` * @example * Calling `withDefault` is _almost_ the same as: * ```ts * oneOf(parser, () => success(fallbackValue)) * ``` * The only difference is that the return type of the parser will always be a success. * @param parser * @param fallbackValue */ export declare const withDefault: (parser: Parser, fallbackValue: T) => InfallibleParser; declare type WithOptionalFields = Simplify<{ [K in RequiredKeys]: Exclude; } & { [K in OptionalKeys]?: Exclude; }>; export { }