UNPKG

2.48 kBTypeScriptView Raw
1import { BaseValidator, StructuredValidator, ExactValidator } from './types';
2/**
3 * Creates a validator which can output subtypes of `BaseT`. E.g.:
4 *
5 * ```ts
6 * const int = makeValidator<number>((input: string) => {
7 * // Implementation details
8 * })
9 * const MAX_RETRIES = int({ choices: [1, 2, 3, 4] })
10 * // Narrows down output type to 1 | 2 | 3 | 4
11 * ```
12 *
13 * @param parseFn - A function to parse and validate input.
14 * @returns A validator which output type is narrowed-down to a subtype of `BaseT`
15 */
16export declare const makeValidator: <BaseT>(parseFn: (input: string) => BaseT) => BaseValidator<BaseT>;
17/**
18 * Creates a validator which output type is exactly T:
19 *
20 * ```ts
21 * const int = makeExactValidator<number>((input: string) => {
22 * // Implementation details
23 * })
24 * const MAX_RETRIES = int({ choices: [1, 2, 3, 4] })
25 * // Output type 'number'
26 * ```
27 *
28 * @param parseFn - A function to parse and validate input.
29 * @returns A validator which output type is exactly `T`
30 */
31export declare const makeExactValidator: <T>(parseFn: (input: string) => T) => ExactValidator<T>;
32/**
33 * This validator is meant for inputs which can produce arbitrary output types (e.g. json).
34 * The typing logic behaves differently from other makers:
35 *
36 * - makeStructuredValidator has no type parameter.
37 * - When no types can be inferred from context, output type defaults to any.
38 * - Otherwise, infers type from `default` or `devDefault`.
39 * - Also generated validators have an output type parameter.
40 * - Finally, the generated validators disallow `choices` parameter.
41 *
42 * Below is an example of a validator for query parameters (e.g. `option1=foo&option2=bar`):
43 *
44 * ```ts
45 * const queryParams = makeStructuredValidator((input: string) => {
46 * const params = new URLSearchParams(input)
47 * return Object.fromEntries(params.entries())
48 * })
49 * const OPTIONS1 = queryParams()
50 * // Output type 'any'
51 * const OPTIONS2 = queryParams({ default: { option1: 'foo', option2: 'bar' } })
52 * // Output type '{ option1: string, option2: string }'
53 * const OPTIONS3 = queryParams<{ option1?: string; option2?: string }>({
54 * default: { option1: 'foo', option2: 'bar' },
55 * })
56 * // Output type '{ option1?: string, option2?: string }'
57 * ```
58 *
59 * @param parseFn - A function to parse and validate input.
60 * @returns A validator which output type is exactly `T`
61 */
62export declare const makeStructuredValidator: (parseFn: (input: string) => unknown) => StructuredValidator;