UNPKG

31.8 kBTypeScriptView Raw
1// Type definitions for yup 0.29
2// Project: https://github.com/jquense/yup
3// Definitions by: Dominik Hardtke <https://github.com/dhardtke>,
4// Vladyslav Tserman <https://github.com/vtserman>,
5// Moreton Bay Regional Council <https://github.com/MoretonBayRC>,
6// Sindre Seppola <https://github.com/sseppola>
7// Yash Kulshrestha <https://github.com/YashdalfTheGray>
8// Vincent Pizzo <https://github.com/vincentjames501>
9// Robert Bullen <https://github.com/robertbullen>
10// Yusuke Sato <https://github.com/sat0yu>
11// Desmond Koh <https://github.com/deskoh>
12// Maurice de Beijer <https://github.com/mauricedb>
13// Kalley Powell <https://github.com/kalley>
14// Elías García <https://github.com/elias-garcia>
15// Ian Sanders <https://github.com/iansan5653>
16// Jay Fong <https://github.com/fjc0k>
17// Lukas Elmer <https://github.com/lukaselmer>
18// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
19// TypeScript Version: 3.6
20
21export function reach<T, C = object>(schema: Schema<T, C>, path: string, value?: any, context?: any): Schema<T, C>;
22export function addMethod<T extends Schema<any>>(
23 schemaCtor: AnySchemaConstructor,
24 name: string,
25 method: (this: T, ...args: any[]) => T,
26): void;
27export function ref(path: string, options?: { contextPrefix: string }): Ref;
28export function lazy<T>(fn: (value: T) => Schema<T>): Lazy;
29export function setLocale(customLocale: LocaleObject): void;
30export function isSchema(obj: any): obj is Schema<any>;
31
32export const mixed: MixedSchemaConstructor;
33export const string: StringSchemaConstructor;
34export const number: NumberSchemaConstructor;
35export const boolean: BooleanSchemaConstructor;
36export const bool: BooleanSchemaConstructor;
37export const date: DateSchemaConstructor;
38export const array: ArraySchemaConstructor;
39export const object: ObjectSchemaConstructor;
40
41export type AnySchemaConstructor =
42 | MixedSchemaConstructor
43 | StringSchemaConstructor
44 | NumberSchemaConstructor
45 | BooleanSchemaConstructor
46 | DateSchemaConstructor
47 | ArraySchemaConstructor
48 | ObjectSchemaConstructor;
49
50export type TestOptionsMessage<Extra extends Record<string, any> = {}, R = any> =
51 | string
52 | ((params: Extra & Partial<TestMessageParams>) => R);
53
54export interface Schema<T, C = object> {
55 type: string;
56 clone(): this;
57 label(label: string): this;
58 meta(metadata: any): this;
59 meta(): any;
60 describe(): SchemaDescription;
61 concat(schema: this): this;
62 validate(value: any, options?: ValidateOptions<C>): Promise<T>;
63 validateSync(value: any, options?: ValidateOptions<C>): T;
64 validateAt(path: string, value: T, options?: ValidateOptions<C>): Promise<T>;
65 validateSyncAt(path: string, value: T, options?: ValidateOptions<C>): T;
66 isValid(value: any, options?: any): Promise<boolean>;
67 isValidSync(value: any, options?: any): value is T;
68 cast(value?: any, options?: any): T;
69 isType(value: any): value is T;
70 strict(isStrict: boolean): this;
71 strip(strip: boolean): this;
72 withMutation(fn: (current: this) => void): void;
73 default(value: T | (() => T)): Schema<T, C>;
74 default(): T;
75 typeError(message?: TestOptionsMessage): this;
76 notOneOf(arrayOfValues: any[], message?: MixedLocale['notOneOf']): this;
77 when(keys: string | any[], builder: WhenOptions<this>): this;
78 transform(fn: TransformFunction<this>): this;
79}
80
81// Note: Using `{} | null | undefined` allows excluding `null` & `undefined`
82// whereas using `any` as the default type would mean that `nullable(false)`,
83// `defined`, and `required` would all have no effect.
84
85export interface MixedSchemaConstructor {
86 // tslint:disable-next-line:no-unnecessary-generics
87 <T = {} | null | undefined, C = object>(): MixedSchema<T, C>;
88 // tslint:disable-next-line:no-unnecessary-generics
89 new <T = {} | null | undefined, C = object>(options?: { type?: string | undefined; [key: string]: any }): MixedSchema<T, C>;
90}
91
92export interface MixedSchema<T extends any = {} | null | undefined, C = object> extends Schema<T, C> {
93 nullable(isNullable?: true): MixedSchema<T | null, C>;
94 nullable(isNullable: false): MixedSchema<Exclude<T, null>, C>;
95 nullable(isNullable?: boolean): MixedSchema<T, C>;
96 required(message?: TestOptionsMessage): MixedSchema<Exclude<T, undefined | null>, C>;
97 defined(): MixedSchema<Exclude<T, undefined>, C>;
98 notRequired(): MixedSchema<T | undefined, C>;
99 optional(): MixedSchema<T | undefined, C>;
100 concat(schema: this): this;
101 concat<U>(schema: Schema<U, C>): MixedSchema<T | U, C>;
102 oneOf<U extends T>(
103 arrayOfValues: ReadonlyArray<U | Ref>,
104 message?: MixedLocale['oneOf'],
105 ): MixedSchema<MaintainOptionality<T, U>, C>;
106 equals<U extends T>(
107 arrayOfValues: ReadonlyArray<U | Ref>,
108 message?: MixedLocale['oneOf'],
109 ): MixedSchema<MaintainOptionality<T, U>, C>;
110 test<U extends T = T>(
111 name: string,
112 message: TestOptionsMessage,
113 test: AssertingTestFunction<U, C>,
114 ): MixedSchema<U, C>;
115 test(name: string, message: TestOptionsMessage, test: TestFunction<unknown, C>): this;
116 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): MixedSchema<U, C>;
117 test(options: TestOptions<Record<string, any>, C>): this;
118 default<U extends T>(value: U | (() => U)): U extends undefined ? MixedSchema<T, C> : MixedSchema<Exclude<T, undefined>, C>;
119 default(): T;
120}
121
122export interface StringSchemaConstructor {
123 // tslint:disable-next-line:no-unnecessary-generics
124 <T extends string | null | undefined = string | undefined, C = object>(): StringSchema<T, C>;
125 // tslint:disable-next-line:no-unnecessary-generics
126 new <T extends string | null | undefined = string | undefined, C = object>(): StringSchema<T, C>;
127}
128
129export interface StringSchema<T extends string | null | undefined = string | undefined, C = object>
130 extends Schema<T, C> {
131 length(limit: number | Ref, message?: StringLocale['length']): StringSchema<T, C>;
132 min(limit: number | Ref, message?: StringLocale['min']): StringSchema<T, C>;
133 max(limit: number | Ref, message?: StringLocale['max']): StringSchema<T, C>;
134 matches(
135 regex: RegExp,
136 messageOrOptions?:
137 | StringLocale['matches']
138 | { message?: StringLocale['matches'] | undefined; excludeEmptyString?: boolean | undefined },
139 ): StringSchema<T, C>;
140 email(message?: StringLocale['email']): StringSchema<T, C>;
141 url(message?: StringLocale['url']): StringSchema<T, C>;
142 uuid(message?: StringLocale['uuid']): StringSchema<T, C>;
143 ensure(): StringSchema<T, C>;
144 trim(message?: StringLocale['trim']): StringSchema<T, C>;
145 lowercase(message?: StringLocale['lowercase']): StringSchema<T, C>;
146 uppercase(message?: StringLocale['uppercase']): StringSchema<T, C>;
147 nullable(isNullable?: true): StringSchema<T | null, C>;
148 nullable(isNullable: false): StringSchema<Exclude<T, null>, C>;
149 nullable(isNullable?: boolean): StringSchema<T, C>;
150 required(message?: TestOptionsMessage): StringSchema<Exclude<T, undefined | null>, C>;
151 defined(): StringSchema<Exclude<T, undefined>, C>;
152 notRequired(): StringSchema<T | undefined, C>;
153 oneOf<U extends T>(
154 arrayOfValues: ReadonlyArray<U | Ref>,
155 message?: MixedLocale['oneOf'],
156 ): StringSchema<MaintainOptionality<T, U>, C>;
157 equals<U extends T>(
158 arrayOfValues: ReadonlyArray<U | Ref>,
159 message?: MixedLocale['oneOf'],
160 ): StringSchema<MaintainOptionality<T, U>, C>;
161 /*
162 All TestFunction generics are intentionally T with (undefined | null) as previous .required / .defined / .nullable
163 will narrow out those types, and tests run for (undefined | null) even if they're not allowed.
164 */
165 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
166 test<U extends T = T>(
167 name: string,
168 message: TestOptionsMessage,
169 test: AssertingTestFunction<U, C>,
170 ): StringSchema<U, C>;
171 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): StringSchema<U, C>;
172 test(options: TestOptions<Record<string, any>, C>): this;
173 optional(): StringSchema<T | undefined, C>;
174 default<U extends T>(value: U | (() => U)): U extends undefined ? StringSchema<T, C> : StringSchema<Exclude<T, undefined>, C>;
175 default(): T;
176}
177
178export interface NumberSchemaConstructor {
179 // tslint:disable-next-line:no-unnecessary-generics
180 <T extends number | null | undefined = number | undefined, C = object>(): NumberSchema<T, C>;
181 // tslint:disable-next-line:no-unnecessary-generics
182 new <T extends number | null | undefined = number | undefined, C = object>(): NumberSchema<T, C>;
183}
184
185export interface NumberSchema<T extends number | null | undefined = number | undefined, C = object>
186 extends Schema<T, C> {
187 min(limit: number | Ref, message?: NumberLocale['min']): NumberSchema<T, C>;
188 max(limit: number | Ref, message?: NumberLocale['max']): NumberSchema<T, C>;
189 lessThan(limit: number | Ref, message?: NumberLocale['lessThan']): NumberSchema<T, C>;
190 moreThan(limit: number | Ref, message?: NumberLocale['moreThan']): NumberSchema<T, C>;
191 positive(message?: NumberLocale['positive']): NumberSchema<T, C>;
192 negative(message?: NumberLocale['negative']): NumberSchema<T, C>;
193 integer(message?: NumberLocale['integer']): NumberSchema<T, C>;
194 truncate(): NumberSchema<T, C>;
195 round(type: 'floor' | 'ceil' | 'trunc' | 'round'): NumberSchema<T, C>;
196 nullable(isNullable?: true): NumberSchema<T | null, C>;
197 nullable(isNullable: false): NumberSchema<Exclude<T, null>, C>;
198 nullable(isNullable?: boolean): NumberSchema<T, C>;
199 required(message?: TestOptionsMessage): NumberSchema<Exclude<T, undefined | null>, C>;
200 defined(): NumberSchema<Exclude<T, undefined>, C>;
201 notRequired(): NumberSchema<T | undefined, C>;
202 oneOf<U extends T>(
203 arrayOfValues: ReadonlyArray<U | Ref>,
204 message?: MixedLocale['oneOf'],
205 ): NumberSchema<MaintainOptionality<T, U>, C>;
206 equals<U extends T>(
207 arrayOfValues: ReadonlyArray<U | Ref>,
208 message?: MixedLocale['oneOf'],
209 ): NumberSchema<MaintainOptionality<T, U>, C>;
210 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
211 test<U extends T = T>(
212 name: string,
213 message: TestOptionsMessage,
214 test: AssertingTestFunction<U, C>,
215 ): NumberSchema<U, C>;
216 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): NumberSchema<U, C>;
217 test(options: TestOptions<Record<string, any>, C>): this;
218 optional(): NumberSchema<T | undefined, C>;
219 default<U extends T>(value: U | (() => U)): U extends undefined ? NumberSchema<T, C> : NumberSchema<Exclude<T, undefined>, C>;
220 default(): T;
221}
222
223export interface BooleanSchemaConstructor {
224 // tslint:disable-next-line:no-unnecessary-generics
225 <T extends boolean | null | undefined = boolean | undefined, C = object>(): BooleanSchema<T, C>;
226 // tslint:disable-next-line:no-unnecessary-generics
227 new <T extends boolean | null | undefined = boolean | undefined, C = object>(): BooleanSchema<T, C>;
228}
229
230export interface BooleanSchema<T extends boolean | null | undefined = boolean | undefined, C = object>
231 extends Schema<T, C> {
232 nullable(isNullable?: true): BooleanSchema<T | null, C>;
233 nullable(isNullable: false): BooleanSchema<Exclude<T, null>, C>;
234 nullable(isNullable?: boolean): BooleanSchema<T, C>;
235 required(message?: TestOptionsMessage): BooleanSchema<Exclude<T, undefined | null>, C>;
236 defined(): BooleanSchema<Exclude<T, undefined>, C>;
237 notRequired(): BooleanSchema<T | undefined, C>;
238 oneOf<U extends T>(
239 arrayOfValues: ReadonlyArray<U | Ref>,
240 message?: MixedLocale['oneOf'],
241 ): BooleanSchema<MaintainOptionality<T, U>, C>;
242 equals<U extends T>(
243 arrayOfValues: ReadonlyArray<U | Ref>,
244 message?: MixedLocale['oneOf'],
245 ): BooleanSchema<MaintainOptionality<T, U>, C>;
246 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
247 test<U extends T = T>(
248 name: string,
249 message: TestOptionsMessage,
250 test: AssertingTestFunction<U, C>,
251 ): BooleanSchema<U, C>;
252 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): BooleanSchema<U, C>;
253 test(options: TestOptions<Record<string, any>, C>): this;
254 optional(): BooleanSchema<T | undefined, C>;
255 default<U extends T>(value: U | (() => U)): U extends undefined ? BooleanSchema<T, C> : BooleanSchema<Exclude<T, undefined>, C>;
256 default(): T;
257}
258
259export interface DateSchemaConstructor {
260 // tslint:disable-next-line:no-unnecessary-generics
261 <T extends Date | string | null | undefined = Date | undefined, C = object>(): DateSchema<T, C>;
262 // tslint:disable-next-line:no-unnecessary-generics
263 new <T extends Date | string | null | undefined = Date | undefined, C = object>(): DateSchema<T, C>;
264}
265
266export interface DateSchema<T extends Date | string | null | undefined = Date | undefined, C = object> extends Schema<T, C> {
267 min(limit: Date | string | Ref, message?: DateLocale['min']): DateSchema<T, C>;
268 max(limit: Date | string | Ref, message?: DateLocale['max']): DateSchema<T, C>;
269 nullable(isNullable?: true): DateSchema<T | null, C>;
270 nullable(isNullable: false): DateSchema<Exclude<T, null>, C>;
271 nullable(isNullable?: boolean): DateSchema<T, C>;
272 required(message?: TestOptionsMessage): DateSchema<Exclude<T, undefined | null>, C>;
273 defined(): DateSchema<Exclude<T, undefined>, C>;
274 notRequired(): DateSchema<T | undefined, C>;
275 oneOf<U extends T>(
276 arrayOfValues: ReadonlyArray<U | Ref>,
277 message?: MixedLocale['oneOf'],
278 ): DateSchema<MaintainOptionality<T, U>, C>;
279 equals<U extends T>(
280 arrayOfValues: ReadonlyArray<U | Ref>,
281 message?: MixedLocale['oneOf'],
282 ): DateSchema<MaintainOptionality<T, U>, C>;
283 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
284 test<U extends T = T>(
285 name: string,
286 message: TestOptionsMessage,
287 test: AssertingTestFunction<U, C>,
288 ): DateSchema<U, C>;
289 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): DateSchema<U, C>;
290 test(options: TestOptions<Record<string, any>, C>): this;
291 optional(): DateSchema<T | undefined, C>;
292 default<U extends T>(value: U | (() => U)): U extends undefined ? DateSchema<T, C> : DateSchema<Exclude<T, undefined>, C>;
293 default(): T;
294}
295
296export interface ArraySchemaConstructor {
297 <T, C = object>(schema?: Schema<T, C>): NotRequiredArraySchema<T, C>;
298 // tslint:disable-next-line:no-unnecessary-generics
299 new <C = object>(): NotRequiredArraySchema<{}, C>;
300}
301
302export interface BasicArraySchema<E, T extends E[] | null | undefined, C = object> extends Schema<T, C> {
303 min(limit: number | Ref, message?: ArrayLocale['min']): this;
304 max(limit: number | Ref, message?: ArrayLocale['max']): this;
305 ensure(): this;
306 compact(
307 rejector?: (value: InferredArrayType<T>, index: number, array: Array<InferredArrayType<T>>) => boolean,
308 ): this;
309
310 // This doesn't narrow the type of the schema like the more primitive oneOf calls
311 // it would be very complex to do that accurately with the subtypes, and it's not
312 // really worth it because the oneOf check is a shallow (==) comparison so it rarely
313 // applies to arrays anyway.
314 oneOf(arrayOfValues: ReadonlyArray<T | Ref | null>, message?: MixedLocale['oneOf']): this;
315 equals(arrayOfValues: ReadonlyArray<T | Ref | null>, message?: MixedLocale['oneOf']): this;
316 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
317 test(options: TestOptions<Record<string, any>, C>): this;
318 innerType: Schema<E, C>;
319}
320
321export interface NotRequiredNullableArraySchema<T, C = object> extends BasicArraySchema<T, T[] | null | undefined, C> {
322 of<U>(type: Schema<U, C>): NotRequiredNullableArraySchema<U, C>;
323 nullable(isNullable?: true): NotRequiredNullableArraySchema<T, C>;
324 nullable(isNullable: false): NotRequiredArraySchema<T, C>;
325 nullable(isNullable?: boolean): ArraySchema<T, C>;
326 required(message?: TestOptionsMessage): ArraySchema<T, C>;
327 defined(): NullableArraySchema<T, C>;
328 notRequired(): NotRequiredNullableArraySchema<T, C>;
329 optional(): NotRequiredNullableArraySchema<T, C>;
330}
331
332export interface NullableArraySchema<T, C = object> extends BasicArraySchema<T, T[] | null, C> {
333 of<U>(type: Schema<U, C>): NullableArraySchema<U, C>;
334 nullable(isNullable?: true): NullableArraySchema<T, C>;
335 nullable(isNullable: false): ArraySchema<T, C>;
336 nullable(isNullable?: boolean): ArraySchema<T, C>;
337 required(message?: TestOptionsMessage): ArraySchema<T, C>;
338 defined(): NullableArraySchema<T, C>;
339 notRequired(): NotRequiredNullableArraySchema<T, C>;
340 optional(): NotRequiredNullableArraySchema<T, C>;
341}
342
343export interface NotRequiredArraySchema<T, C = object> extends BasicArraySchema<T, T[] | undefined, C> {
344 of<U>(type: Schema<U, C>): NotRequiredArraySchema<U, C>;
345 nullable(isNullable?: true): NotRequiredNullableArraySchema<T, C>;
346 nullable(isNullable: false): NotRequiredArraySchema<T, C>;
347 nullable(isNullable: boolean): ArraySchema<T, C>;
348 required(message?: TestOptionsMessage): ArraySchema<T, C>;
349 defined(): ArraySchema<T, C>;
350 notRequired(): NotRequiredArraySchema<T, C>;
351 optional(): NotRequiredArraySchema<T, C>;
352}
353
354export interface ArraySchema<T, C = object> extends BasicArraySchema<T, T[], C> {
355 of<U>(type: Schema<U, C>): ArraySchema<U, C>;
356 nullable(isNullable?: true): NullableArraySchema<T, C>;
357 nullable(isNullable: false | boolean): ArraySchema<T, C>;
358 required(message?: TestOptionsMessage): ArraySchema<T, C>;
359 defined(): ArraySchema<T, C>;
360 notRequired(): NotRequiredArraySchema<T, C>;
361 optional(): NotRequiredArraySchema<T, C>;
362}
363
364export type ObjectSchemaDefinition<T extends object | null | undefined, C = object> = {
365 // This shouldn't be necessary because MixedSchema extends Schema, but type
366 // inference only works with it this way - otherwise when you use a mixed
367 // field in object schema, it will type as `unknown`. Not sure why that is -
368 // maybe some sort of inference depth limit?
369 [field in keyof T]: Schema<T[field], C> | MixedSchema<T[field], C> | Ref;
370};
371
372/**
373 * Merges two interfaces. For properties in common, property types from `U` trump those of `T`.
374 * This is conducive to the functionality of
375 * [yup's `object.shape()` method](https://www.npmjs.com/package/yup#objectshapefields-object-nosortedges-arraystring-string-schema).
376 */
377export type Shape<T extends object | null | undefined, U extends object> =
378 | ({ [P in keyof T]: P extends keyof U ? U[P] : T[P] } & U)
379 | PreserveOptionals<T>;
380
381export interface ObjectSchemaConstructor {
382 <T extends object, C = object>(fields?: ObjectSchemaDefinition<T, C>): ObjectSchema<T | undefined, C>;
383 // tslint:disable-next-line:no-unnecessary-generics
384 new <C = object>(): ObjectSchema<{}, C>;
385}
386
387export interface ObjectSchema<T extends object | null | undefined = object | undefined, C = object>
388 extends Schema<T, C> {
389 fields: {
390 [k in keyof T]: Schema<T[k], C>;
391 };
392 shape<U extends object>(
393 fields: ObjectSchemaDefinition<U, C>,
394 noSortEdges?: Array<[string, string]>,
395 ): ObjectSchema<Shape<T, U>, C>;
396 from(fromKey: string, toKey: string, alias?: boolean): ObjectSchema<T, C>;
397 noUnknown(onlyKnownKeys?: boolean, message?: ObjectLocale['noUnknown']): ObjectSchema<T, C>;
398 unknown(allow?: boolean, message?: ObjectLocale['noUnknown']): ObjectSchema<T, C>;
399 transformKeys(callback: (key: any) => any): void;
400 camelCase(): ObjectSchema<T, C>;
401 snakeCase(): ObjectSchema<T, C>;
402 constantCase(): ObjectSchema<T, C>;
403 nullable(isNullable?: true): ObjectSchema<T | null, C>;
404 nullable(isNullable: false): ObjectSchema<Exclude<T, null>, C>;
405 nullable(isNullable?: boolean): ObjectSchema<T, C>;
406 required(message?: TestOptionsMessage): ObjectSchema<Exclude<T, undefined | null>, C>;
407 defined(): ObjectSchema<Exclude<T, undefined>, C>;
408 notRequired(): ObjectSchema<T | undefined, C>;
409 optional(): ObjectSchema<T | undefined, C>;
410 concat(schema: this): this;
411 concat<U extends object>(schema: ObjectSchema<U, C>): ObjectSchema<T & U, C>;
412 oneOf<U extends T>(arrayOfValues: ReadonlyArray<U | Ref>, message?: MixedLocale['oneOf']): ObjectSchema<U, C>;
413 equals<U extends T>(arrayOfValues: ReadonlyArray<U | Ref>, message?: MixedLocale['oneOf']): ObjectSchema<U, C>;
414 test(name: string, message: TestOptionsMessage, test: TestFunction<T | undefined | null, C>): this;
415 test<U extends T = T>(
416 name: string,
417 message: TestOptionsMessage,
418 test: AssertingTestFunction<U, C>,
419 ): ObjectSchema<U, C>;
420 test<U extends T = T>(options: AssertingTestOptions<U, Record<string, any>, C>): ObjectSchema<U, C>;
421 test(options: TestOptions<Record<string, any>, C>): this;
422 default<U extends T>(value: U | (() => U)): U extends undefined ? ObjectSchema<T, C> : ObjectSchema<Exclude<T, undefined>, C>;
423 default(): T;
424}
425
426export type TestFunction<T = unknown, C = object> = (
427 this: TestContext<C>,
428 value: T,
429 context: TestContext<C>
430) => boolean | ValidationError | Promise<boolean | ValidationError>;
431export type AssertingTestFunction<T, C> = (this: TestContext<C>, value: any, context: TestContext<C>) => value is T;
432
433export type TransformFunction<T> = (this: T, value: any, originalValue: any) => any;
434
435export interface WhenOptionsBuilderFunction<T> {
436 (value: any, schema: T): T;
437 (v1: any, v2: any, schema: T): T;
438 (v1: any, v2: any, v3: any, schema: T): T;
439 (v1: any, v2: any, v3: any, v4: any, schema: T): T;
440}
441
442export type WhenOptionsBuilderObjectIs = ((...values: any[]) => boolean) | boolean | number | null | object | string;
443
444export type WhenOptionsBuilderObject =
445 | {
446 is: WhenOptionsBuilderObjectIs;
447 then: any;
448 otherwise: any;
449 }
450 | object;
451
452export type WhenOptions<T> = WhenOptionsBuilderFunction<T> | WhenOptionsBuilderObject;
453
454export interface TestContext<C = object> {
455 path: string;
456 options: ValidateOptions<C>;
457 parent: any;
458 schema: Schema<any, C>;
459 originalValue: any;
460 resolve: (value: any) => any;
461 createError: (params?: { path?: string | undefined; message?: string | undefined; params?: object | undefined }) => ValidationError;
462}
463
464export interface ValidateOptions<C = object> {
465 /**
466 * Only validate the input, and skip and coercion or transformation. Default - false
467 */
468 strict?: boolean | undefined;
469 /**
470 * Return from validation methods on the first error rather than after all validations run. Default - true
471 */
472 abortEarly?: boolean | undefined;
473 /**
474 * Remove unspecified keys from objects. Default - false
475 */
476 stripUnknown?: boolean | undefined;
477 /**
478 * When false validations will not descend into nested schema (relevant for objects or arrays). Default - true
479 */
480 recursive?: boolean | undefined;
481 /**
482 * Any context needed for validating schema conditions (see: when())
483 */
484 context?: C | undefined;
485}
486
487export interface TestMessageParams {
488 path: string;
489 value: any;
490 originalValue: any;
491 label: string;
492}
493
494interface BaseTestOptions<P extends Record<string, any>, C = object> {
495 /**
496 * Unique name identifying the test. Required for exclusive tests.
497 */
498 name?: string | undefined;
499
500 /**
501 * Test function, determines schema validity
502 */
503 test: TestFunction<unknown, C>;
504
505 /**
506 * The validation error message
507 */
508 message?: TestOptionsMessage<P> | undefined;
509
510 /**
511 * Values passed to message for interpolation
512 */
513 params?: P | undefined;
514
515 /**
516 * Mark the test as exclusive, meaning only one of the same can be active at once
517 */
518 exclusive?: boolean | undefined;
519}
520
521interface NonExclusiveTestOptions<P extends Record<string, any>, C> extends BaseTestOptions<P, C> {
522 exclusive?: false | undefined;
523}
524
525interface ExclusiveTestOptions<P extends Record<string, any>, C> extends BaseTestOptions<P, C> {
526 exclusive: true;
527 name: string;
528}
529
530interface NonExclusiveAssertingTestOptions<U, P extends Record<string, any>, C> extends NonExclusiveTestOptions<P, C> {
531 test: AssertingTestFunction<U, C>;
532}
533
534interface ExclusiveAssertingTestOptions<U, P extends Record<string, any>, C> extends ExclusiveTestOptions<P, C> {
535 test: AssertingTestFunction<U, C>;
536}
537
538export type TestOptions<P extends Record<string, any> = {}, C = object> =
539 | NonExclusiveTestOptions<P, C>
540 | ExclusiveTestOptions<P, C>;
541
542export type AssertingTestOptions<U, P extends Record<string, any> = {}, C = object> =
543 | NonExclusiveAssertingTestOptions<U, P, C>
544 | ExclusiveAssertingTestOptions<U, P, C>;
545
546export interface SchemaFieldRefDescription {
547 type: 'ref';
548 key: string;
549}
550
551export interface SchemaFieldInnerTypeDescription
552 extends Pick<SchemaDescription, Exclude<keyof SchemaDescription, 'fields'>> {
553 innerType?: SchemaFieldDescription | undefined;
554}
555
556export type SchemaFieldDescription = SchemaDescription | SchemaFieldRefDescription | SchemaFieldInnerTypeDescription;
557
558export interface SchemaDescription {
559 type: string;
560 label: string;
561 meta: object;
562 tests: Array<{ name: string; params: { [k: string]: any } }>;
563 fields: Record<string, SchemaFieldDescription>;
564}
565
566// ValidationError works a lot more like a class vs. a constructor
567// function that returns an interface. It's also got a couple of
568// static methods and it inherits from the generic Error class in
569// the [yup codebase][1].
570// [1]: (https://github.com/jquense/yup/blob/master/src/ValidationError.js)
571export class ValidationError extends Error {
572 name: string;
573 message: string;
574 value: any;
575 /**
576 * A string, indicating where there error was thrown. path is empty at the root level.
577 */
578 path: string;
579 type: any;
580 /**
581 * array of error messages
582 */
583 errors: string[];
584
585 /**
586 * In the case of aggregate errors, inner is an array of ValidationErrors throw earlier in the validation chain.
587 */
588 inner: ValidationError[];
589 params?: object | undefined;
590
591 static isError(err: any): err is ValidationError;
592 static formatError(message: string | ((params?: any) => string), params?: any): string | ((params?: any) => string);
593
594 constructor(errors: string | string[], value: any, path: string, type?: any);
595}
596
597// It is tempting to declare `Ref` very simply, but there are problems with these approaches:
598//
599// * `type Ref = Record<string, any>;` - This is essentially how it was originally declared, but
600// just about any object satisfies this contract, which makes the type declaration too loose to
601// be useful.
602//
603// * `type Ref = object;` - This is a variation on the previous bullet in that it is too loose.
604//
605// * `class Ref {}` - This is yet another variation that is too loose.
606//
607// * `type Ref = void;` - This works and the emitted JavaScript is just fine, but it results in some
608// confusing IntelliSense, e.g it looks like the `ref()` returns `void`, which is not the case.
609//
610// The solution is twofold. 1.) Declare it as a class with a private constructor to prevent it from
611// being instantiated by anything but the `ref()` factory function, and; 2.) declare a private
612// readonly property (that yup actually places on the prototype) to force it to be structurally
613// incompatible with any other object type.
614
615/**
616 * `Ref` is an opaque type that is internal to yup. Creating a `Ref` instance is accomplished via the `ref()` factory
617 * function.
618 */
619export class Ref {
620 private constructor();
621 private readonly __isYupRef: true;
622}
623
624export interface Lazy extends Schema<any> {}
625
626export interface FormatErrorParams {
627 path: string;
628 type: string;
629 value?: any;
630 originalValue?: any;
631}
632
633export type LocaleValue = string | ((params: FormatErrorParams) => string);
634
635export interface MixedLocale {
636 default?: TestOptionsMessage | undefined;
637 required?: TestOptionsMessage | undefined;
638 oneOf?: TestOptionsMessage<{ values: any }> | undefined;
639 notOneOf?: TestOptionsMessage<{ values: any }> | undefined;
640 notType?: LocaleValue | undefined;
641 defined?: TestOptionsMessage | undefined;
642}
643
644export interface StringLocale {
645 length?: TestOptionsMessage<{ length: number }> | undefined;
646 min?: TestOptionsMessage<{ min: number }> | undefined;
647 max?: TestOptionsMessage<{ max: number }> | undefined;
648 matches?: TestOptionsMessage<{ regex: RegExp }> | undefined;
649 email?: TestOptionsMessage<{ regex: RegExp }> | undefined;
650 url?: TestOptionsMessage<{ regex: RegExp }> | undefined;
651 uuid?: TestOptionsMessage<{ regex: RegExp }> | undefined;
652 trim?: TestOptionsMessage | undefined;
653 lowercase?: TestOptionsMessage | undefined;
654 uppercase?: TestOptionsMessage | undefined;
655}
656
657export interface NumberLocale {
658 min?: TestOptionsMessage<{ min: number }> | undefined;
659 max?: TestOptionsMessage<{ max: number }> | undefined;
660 lessThan?: TestOptionsMessage<{ less: number }> | undefined;
661 moreThan?: TestOptionsMessage<{ more: number }> | undefined;
662 notEqual?: TestOptionsMessage<{ notEqual: number }> | undefined;
663 positive?: TestOptionsMessage<{ more: number }> | undefined;
664 negative?: TestOptionsMessage<{ less: number }> | undefined;
665 integer?: TestOptionsMessage | undefined;
666}
667
668export interface DateLocale {
669 min?: TestOptionsMessage<{ min: Date | string }> | undefined;
670 max?: TestOptionsMessage<{ max: Date | string }> | undefined;
671}
672
673export interface ObjectLocale {
674 noUnknown?: TestOptionsMessage<{ unknown: string }> | undefined;
675}
676
677export interface ArrayLocale {
678 min?: TestOptionsMessage<{ min: number }> | undefined;
679 max?: TestOptionsMessage<{ max: number }> | undefined;
680}
681
682export interface LocaleObject {
683 mixed?: MixedLocale | undefined;
684 string?: StringLocale | undefined;
685 number?: NumberLocale | undefined;
686 date?: DateLocale | undefined;
687 boolean?: {} | undefined;
688 object?: ObjectLocale | undefined;
689 array?: ArrayLocale | undefined;
690}
691
692export type InferType<T> = T extends Schema<infer P> ? InnerInferType<P> : never;
693
694// Shut off automatic exporting after this statement
695export {};
696
697type KeyOfUndefined<T> = {
698 [P in keyof T]-?: undefined extends T[P] ? P : never;
699}[keyof T];
700
701type PreserveNull<T> = T extends null ? null : never;
702type PreserveUndefined<T> = T extends undefined ? undefined : never;
703type PreserveOptionals<T> = PreserveNull<T> | PreserveUndefined<T>;
704type Id<T> = {
705 [K in keyof T]: T[K] extends object ? InnerInferType<T[K]> : T[K];
706};
707type RequiredProps<T> = Pick<T, Exclude<keyof T, KeyOfUndefined<T>>>;
708type NotRequiredProps<T> = Partial<Pick<T, KeyOfUndefined<T>>>;
709type InnerInferType<T> =
710 | (T extends Array<infer T> ? InnerInferTypeArray<T> : Id<NotRequiredProps<T> & RequiredProps<T>>)
711 | PreserveOptionals<T>;
712interface InnerInferTypeArray<T> extends Array<InnerInferType<T>> {}
713type InferredArrayType<T> = T extends Array<infer U> ? U : T;
714/** If `T` is optional, returns optional `U`. */
715type MaintainOptionality<T, U> = T extends undefined ? U | undefined : U;
716
\No newline at end of file