-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
README.md
959 lines (770 loc) Β· 23.3 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
<img src="assets/header-round-medium.png" width="100%" align="center" />
<p align="right">
<i>If you use this repo, star it β¨</i>
</p>
# Stop typing twice π
ββοΈ
A lot of projects use JSON schemas for runtime data validation along with TypeScript for static type checking.
Their code may look like this:
```typescript
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
};
type Dog = {
name: string;
age: number;
hobbies?: string[];
favoriteFood?: "pizza" | "taco" | "fries";
};
```
Both objects carry similar if not exactly the same information. This is a code duplication that can annoy developers and introduce bugs if not properly maintained.
That's when `json-schema-to-ts` comes to the rescue πͺ
## FromSchema
The `FromSchema` method lets you infer TS types directly from JSON schemas:
```typescript
import { FromSchema } from "json-schema-to-ts";
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
} as const;
type Dog = FromSchema<typeof dogSchema>;
// => Will infer the same type as above
```
Schemas can even be nested, as long as you don't forget the `as const` statement:
```typescript
const catSchema = { ... } as const;
const petSchema = {
anyOf: [dogSchema, catSchema],
} as const;
type Pet = FromSchema<typeof petSchema>;
// => Will work π
```
The `as const` statement is used so that TypeScript takes the schema definition to the word (e.g. _true_ is interpreted as the _true_ constant and not widened as _boolean_). It is pure TypeScript and has zero impact on the compiled code.
If you don't mind impacting the compiled code, you can use the `asConst` util, which simply returns the schema while narrowing its inferred type.
```typescript
import { asConst } from "json-schema-to-ts";
const dogSchema = asConst({
type: "object",
...
});
type Dog = FromSchema<typeof dogSchema>;
// => Will work as well π
```
Since TS 4.9, you can also use the `satisfies` operator to benefit from type-checking and autocompletion:
```typescript
import type { JSONSchema } from "json-schema-to-ts";
const dogSchema = {
// Type-checked and autocompleted π
type: "object"
...
} as const satisfies JSONSchema
type Dog = FromSchema<typeof dogSchema>
// => Still work π
```
## Why use `json-schema-to-ts`?
If you're looking for runtime validation with added types, libraries like [yup](https://github.com/jquense/yup), [zod](https://github.com/vriad/zod) or [runtypes](https://github.com/pelotom/runtypes) may suit your needs while being easier to use!
On the other hand, JSON schemas have the benefit of being widely used, more versatile and reusable (swaggers, APIaaS...).
If you prefer to stick to them and can define your schemas in TS instead of JSON (importing JSONs `as const` is not available yet), then `json-schema-to-ts` is made for you:
- β
**Schema validation** `FromSchema` raises TS errors on invalid schemas, based on [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema)'s definitions
- β¨ **No impact on compiled code**: `json-schema-to-ts` only operates in type space. And after all, what's lighter than a dev-dependency?
- πΈ **DRYness**: Less code means less embarrassing typos
- π€ **Real-time consistency**: See that `string` that you used instead of an `enum`? Or this `additionalProperties` you confused with `additionalItems`? Or forgot entirely? Well, `json-schema-to-ts` does!
- π§ **Reliability**: `FromSchema` is extensively tested against [AJV](https://github.com/ajv-validator/ajv), and covers all the use cases that can be handled by TS for now\*
- ποΈββοΈ **Help on complex schemas**: Get complex schemas right first time with instantaneous typing feedbacks! For instance, it's not obvious the following schema can never be validated:
```typescript
const addressSchema = {
type: "object",
allOf: [
{
properties: {
street: { type: "string" },
city: { type: "string" },
state: { type: "string" },
},
required: ["street", "city", "state"],
},
{
properties: {
type: { enum: ["residential", "business"] },
},
},
],
additionalProperties: false,
} as const;
```
But it is with `FromSchema`!
```typescript
type Address = FromSchema<typeof addressSchema>;
// => never π
```
> \*If `json-schema-to-ts` misses one of your use case, feel free to [open an issue](https://github.com/ThomasAribart/json-schema-to-ts/issues) π€
## Table of content
- [Installation](#installation)
- [Use cases](#use-cases)
- [Const](#const)
- [Enums](#enums)
- [Primitive types](#primitive-types)
- [Nullable](#nullable)
- [Arrays](#arrays)
- [Tuples](#tuples)
- [Objects](#objects)
- [Combining schemas](#combining-schemas)
- [AnyOf](#anyof)
- [AllOf](#allof)
- [OneOf](#oneof)
- [Not](#not)
- [If/Then/Else](#ifthenelse)
- [Definitions](#definitions)
- [References](#references)
- [Deserialization](#deserialization)
- [Extensions](#extensions)
- [Typeguards](#typeguards)
- [Validators](#validators)
- [Compilers](#compilers)
- [FAQ](#frequently-asked-questions)
## Installation
```bash
# npm
npm install --save-dev json-schema-to-ts
# yarn
yarn add --dev json-schema-to-ts
```
> `json-schema-to-ts` requires TypeScript 4.3+. Using `strict` mode is required, as well as (apparently) turning off [`noStrictGenericChecks`](https://www.typescriptlang.org/tsconfig#noStrictGenericChecks).
## Use cases
### Const
```typescript
const fooSchema = {
const: "foo",
} as const;
type Foo = FromSchema<typeof fooSchema>;
// => "foo"
```
### Enums
```typescript
const enumSchema = {
enum: [true, 42, { foo: "bar" }],
} as const;
type Enum = FromSchema<typeof enumSchema>;
// => true | 42 | { foo: "bar"}
```
You can also go full circle with typescript `enums`.
```typescript
enum Food {
Pizza = "pizza",
Taco = "taco",
Fries = "fries",
}
const enumSchema = {
enum: Object.values(Food),
} as const;
type Enum = FromSchema<typeof enumSchema>;
// => Food
```
### Primitive types
```typescript
const primitiveTypeSchema = {
type: "null", // "boolean", "string", "integer", "number"
} as const;
type PrimitiveType = FromSchema<typeof primitiveTypeSchema>;
// => null, boolean, string or number
```
```typescript
const primitiveTypesSchema = {
type: ["null", "string"],
} as const;
type PrimitiveTypes = FromSchema<typeof primitiveTypesSchema>;
// => null | string
```
> For more complex types, refinment keywords like `required` or `additionalItems` will apply π
### Nullable
```typescript
const nullableSchema = {
type: "string",
nullable: true,
} as const;
type Nullable = FromSchema<typeof nullableSchema>;
// => string | null
```
### Arrays
```typescript
const arraySchema = {
type: "array",
items: { type: "string" },
} as const;
type Array = FromSchema<typeof arraySchema>;
// => string[]
```
### Tuples
```typescript
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...unknown[]]
```
`FromSchema` supports the `additionalItems` keyword:
```typescript
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: false,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string]
```
```typescript
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: { type: "number" },
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...number[]]
```
...as well as the `minItems` and `maxItems` keywords:
```typescript
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
minItems: 1,
maxItems: 2,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [boolean] | [boolean, string]
```
> Additional items will only work if Typescript's `strictNullChecks` option is activated
### Objects
```typescript
const objectSchema = {
type: "object",
properties: {
foo: { type: "string" },
bar: { type: "number" },
},
required: ["foo"],
} as const;
type Object = FromSchema<typeof objectSchema>;
// => { [x: string]: unknown; foo: string; bar?: number; }
```
`FromSchema` partially supports the `additionalProperties` and `patternProperties` keywords:
- `additionalProperties` can be used to deny additional properties.
```typescript
const closedObjectSchema = {
...objectSchema,
additionalProperties: false,
} as const;
type Object = FromSchema<typeof closedObjectSchema>;
// => { foo: string; bar?: number; }
```
- Used on their own, `additionalProperties` and/or `patternProperties` can be used to type unnamed properties.
```typescript
const openObjectSchema = {
type: "object",
additionalProperties: {
type: "boolean",
},
patternProperties: {
"^S": { type: "string" },
"^I": { type: "integer" },
},
} as const;
type Object = FromSchema<typeof openObjectSchema>;
// => { [x: string]: string | number | boolean }
```
- However, when used in combination with the `properties` keyword, extra properties will always be typed as `unknown` to avoid conflicts.
## Combining schemas
### AnyOf
```typescript
const anyOfSchema = {
anyOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
},
],
} as const;
type AnyOf = FromSchema<typeof anyOfSchema>;
// => string | string[]
```
`FromSchema` will correctly infer factored schemas:
```typescript
const factoredSchema = {
type: "object",
properties: {
bool: { type: "boolean" },
},
required: ["bool"],
anyOf: [
{
properties: {
str: { type: "string" },
},
required: ["str"],
},
{
properties: {
num: { type: "number" },
},
},
],
} as const;
type Factored = FromSchema<typeof factoredSchema>;
// => {
// [x:string]: unknown;
// bool: boolean;
// str: string;
// } | {
// [x:string]: unknown;
// bool: boolean;
// num?: number;
// }
```
### OneOf
`FromSchema` will parse the `oneOf` keyword in the same way as `anyOf`:
```typescript
const catSchema = {
type: "object",
oneOf: [
{
properties: {
name: { type: "string" },
},
required: ["name"],
},
{
properties: {
color: { enum: ["black", "brown", "white"] },
},
},
],
} as const;
type Cat = FromSchema<typeof catSchema>;
// => {
// [x: string]: unknown;
// name: string;
// } | {
// [x: string]: unknown;
// color?: "black" | "brown" | "white";
// }
// => Error will NOT be raised π±
const invalidCat: Cat = { name: "Garfield" };
```
### AllOf
```typescript
const addressSchema = {
type: "object",
allOf: [
{
properties: {
address: { type: "string" },
city: { type: "string" },
state: { type: "string" },
},
required: ["address", "city", "state"],
},
{
properties: {
type: { enum: ["residential", "business"] },
},
},
],
} as const;
type Address = FromSchema<typeof addressSchema>;
// => {
// [x: string]: unknown;
// address: string;
// city: string;
// state: string;
// type?: "residential" | "business";
// }
```
### Not
Exclusions require heavy computations, that can sometimes be aborted by Typescript and end up in `any` inferred types. For this reason, they are not activated by default: You can opt-in with the `parseNotKeyword` option.
```typescript
const tupleSchema = {
type: "array",
items: [{ const: 1 }, { const: 2 }],
additionalItems: false,
not: {
const: [1],
},
} as const;
type Tuple = FromSchema<typeof tupleSchema, { parseNotKeyword: true }>;
// => [] | [1, 2]
```
```typescript
const primitiveTypeSchema = {
not: {
type: ["array", "object"],
},
} as const;
type PrimitiveType = FromSchema<
typeof primitiveTypeSchema,
{ parseNotKeyword: true }
>;
// => null | boolean | number | string
```
In objects and tuples, the exclusion will propagate to properties/items if it can collapse on a single one.
```typescript
// π Can be propagated on "animal" property
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog", "boat"] },
},
not: {
properties: { animal: { const: "boat" } },
},
required: ["animal"],
additionalProperties: false,
} as const;
type Pet = FromSchema<typeof petSchema, { parseNotKeyword: true }>;
// => { animal: "cat" | "dog" }
```
```typescript
// β Cannot be propagated
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog"] },
color: { enum: ["black", "brown", "white"] },
},
not: {
const: { animal: "cat", color: "white" },
},
required: ["animal", "color"],
additionalProperties: false,
} as const;
type Pet = FromSchema<typeof petSchema, { parseNotKeyword: true }>;
// => { animal: "cat" | "dog", color: "black" | "brown" | "white" }
```
As some actionable keywords are not yet parsed, exclusions that resolve to `never` are granted the benefit of the doubt and omitted. For the moment, `FromSchema` assumes that you are not crafting unvalidatable exclusions.
```typescript
const oddNumberSchema = {
type: "number",
not: { multipleOf: 2 },
} as const;
type OddNumber = FromSchema<typeof oddNumberSchema, { parseNotKeyword: true }>;
// => should and will resolve to "number"
const incorrectSchema = {
type: "number",
not: { bogus: "option" },
} as const;
type Incorrect = FromSchema<typeof incorrectSchema, { parseNotKeyword: true }>;
// => should resolve to "never" but will still resolve to "number"
```
Also, keep in mind that TypeScript misses [refinment types](https://en.wikipedia.org/wiki/Refinement_type):
```typescript
const goodLanguageSchema = {
type: "string",
not: {
enum: ["Bummer", "Silly", "Lazy sod !"],
},
} as const;
type GoodLanguage = FromSchema<
typeof goodLanguageSchema,
{ parseNotKeyword: true }
>;
// => string
```
### If/Then/Else
For the same reason as the `Not` keyword, conditions parsing is not activated by default: You can opt-in with the `parseIfThenElseKeywords` option.
```typescript
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog"] },
dogBreed: { enum: Object.values(DogBreed) },
catBreed: { enum: Object.values(CatBreed) },
},
required: ["animal"],
if: {
properties: {
animal: { const: "dog" },
},
},
then: {
required: ["dogBreed"],
not: { required: ["catBreed"] },
},
else: {
required: ["catBreed"],
not: { required: ["dogBreed"] },
},
additionalProperties: false,
} as const;
type Pet = FromSchema<typeof petSchema, { parseIfThenElseKeywords: true }>;
// => {
// animal: "dog";
// dogBreed: DogBreed;
// catBreed?: CatBreed | undefined
// } | {
// animal: "cat";
// catBreed: CatBreed;
// dogBreed?: DogBreed | undefined
// }
```
> βοΈ `FromSchema` computes the resulting type as `(If β© Then) βͺ (Β¬If β© Else)`. While correct in theory, remember that the `not` keyword is not perfectly assimilated, which may become an issue in some complex schemas.
### Definitions
```typescript
const userSchema = {
type: "object",
properties: {
name: { $ref: "#/$defs/name" },
age: { $ref: "#/$defs/age" },
},
required: ["name", "age"],
additionalProperties: false,
$defs: {
name: { type: "string" },
age: { type: "integer" },
},
} as const;
type User = FromSchema<typeof userSchema>;
// => {
// name: string;
// age: number;
// }
```
> βοΈ Wether in definitions or references, `FromSchema` will not work on recursive schemas for now.
### References
Unlike run-time validator classes like [AJV](https://github.com/ajv-validator/ajv), TS types cannot withhold internal states. Thus, they cannot keep any identified schemas in memory.
But you can hydrate them via the `references` option:
```typescript
const userSchema = {
$id: "http://example.com/schemas/user.json",
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
},
required: ["name", "age"],
additionalProperties: false,
} as const;
const usersSchema = {
type: "array",
items: {
$ref: "http://example.com/schemas/user.json",
},
} as const;
type Users = FromSchema<
typeof usersSchema,
{ references: [typeof userSchema] }
>;
// => {
// name: string;
// age: string;
// }[]
const anotherUsersSchema = {
$id: "http://example.com/schemas/users.json",
type: "array",
items: { $ref: "user.json" },
} as const;
// => Will work as well π
```
## Deserialization
You can specify deserialization patterns with the `deserialize` option:
```typescript
const userSchema = {
type: "object",
properties: {
name: { type: "string" },
email: {
type: "string",
format: "email",
},
birthDate: {
type: "string",
format: "date-time",
},
},
required: ["name", "email", "birthDate"],
additionalProperties: false,
} as const;
type Email = string & { brand: "email" };
type User = FromSchema<
typeof userSchema,
{
deserialize: [
{
pattern: {
type: "string";
format: "email";
};
output: Email;
},
{
pattern: {
type: "string";
format: "date-time";
};
output: Date;
},
];
}
>;
// => {
// name: string;
// email: Email;
// birthDate: Date;
// }
```
## Extensions
If you need to extend the JSON Schema spec with custom properties, use the `ExtendedJSONSchema` and `FromExtendedSchema` types to benefit from `json-schema-to-ts`:
```typescript
import type { ExtendedJSONSchema, FromExtendedSchema } from "json-schema-to-ts";
type CustomProps = {
numberType: "int" | "float" | "bigInt";
};
const bigIntSchema = {
type: "number",
numberType: "bigInt",
// π Ensures mySchema is correct (includes extension)
} as const satisfies ExtendedJSONSchema<CustomProps>;
type BigInt = FromExtendedSchema<
CustomProps,
typeof bigIntSchema,
{
// π Works very well with the deserialize option!
deserialize: [
{
pattern: {
type: "number";
numberType: "bigInt";
};
output: bigint;
},
];
}
>;
```
## Typeguards
You can use `FromSchema` to implement your own typeguard:
```typescript
import { FromSchema, Validator } from "json-schema-to-ts";
// It's important to:
// - Explicitely type your validator as Validator
// - Use FromSchema as the default value of a 2nd generic first
const validate: Validator = <S extends JSONSchema, T = FromSchema<S>>(
schema: S,
data: unknown
): data is T => {
const isDataValid: boolean = ... // Implement validation here
return isDataValid;
};
const petSchema = { ... } as const
let data: unknown;
if (validate(petSchema, data)) {
const { name, ... } = data; // data is typed as Pet π
}
```
If needed, you can provide `FromSchema` options and additional validation options to the `Validator` type:
```typescript
type FromSchemaOptions = { parseNotKeyword: true };
type ValidationOptions = [{ fastValidate: boolean }]
const validate: Validator<FromSchemaOptions, ValidationOptions> = <
S extends JSONSchema,
T = FromSchema<S, FromSchemaOptions>
>(
schema: S,
data: unknown,
...validationOptions: ValidationOptions
): data is T => { ... };
```
`json-schema-to-ts` also exposes two helpers to write type guards. They don't impact the code that you wrote (they simply `return` it), but turn it into type guards.
You can use them to wrap either [`validators`](#validator) or [`compilers`](#compiler).
### Validators
A validator is a function that receives a schema plus some data, and returns `true` if the data is valid compared to the schema, `false` otherwise.
You can use the `wrapValidatorAsTypeGuard` helper to turn validators into type guards. Here is an implementation with [ajv](https://ajv.js.org/):
```typescript
import Ajv from "ajv";
import { $Validator, wrapValidatorAsTypeGuard } from "json-schema-to-ts";
const ajv = new Ajv();
// The initial validator definition is up to you
// ($Validator is prefixed with $ to differ from resulting type guard)
const $validate: $Validator = (schema, data) => ajv.validate(schema, data);
const validate = wrapValidatorAsTypeGuard($validate);
const petSchema = { ... } as const;
let data: unknown;
if (validate(petSchema, data)) {
const { name, ... } = data; // data is typed as Pet π
}
```
If needed, you can provide `FromSchema` options and additional validation options as generic types:
```typescript
type FromSchemaOptions = { parseNotKeyword: true };
type ValidationOptions = [{ fastValidate: boolean }]
const $validate: $Validator<ValidationOptions> = (
schema,
data,
...validationOptions // typed as ValidationOptions
) => { ... };
// validate will inherit from ValidationOptions
const validate = wrapValidatorAsTypeGuard($validate);
// with special FromSchemaOptions
// (ValidationOptions needs to be re-provided)
const validate = wrapValidatorAsTypeGuard<
FromSchemaOptions,
ValidationOptions
>($validate);
```
### Compilers
A compiler is a function that takes a schema as an input and returns a data validator for this schema as an output.
You can use the `wrapCompilerAsTypeGuard` helper to turn compilers into type guard builders. Here is an implementation with [ajv](https://ajv.js.org/):
```typescript
import Ajv from "ajv";
import { $Compiler, wrapCompilerAsTypeGuard } from "json-schema-to-ts";
// The initial compiler definition is up to you
// ($Compiler is prefixed with $ to differ from resulting type guard)
const $compile: $Compiler = (schema) => ajv.compile(schema);
const compile = wrapCompilerAsTypeGuard($compile);
const petSchema = { ... } as const;
const isPet = compile(petSchema);
let data: unknown;
if (isPet(data)) {
const { name, ... } = data; // data is typed as Pet π
}
```
If needed, you can provide `FromSchema` options, additional compiling and validation options as generic types:
```typescript
type FromSchemaOptions = { parseNotKeyword: true };
type CompilingOptions = [{ fastCompile: boolean }];
type ValidationOptions = [{ fastValidate: boolean }];
const $compile: $Compiler<CompilingOptions, ValidationOptions> = (
schema,
...compilingOptions // typed as CompilingOptions
) => {
...
return (
data,
...validationOptions // typed as ValidationOptions
) => { ... };
};
// compile will inherit from all options
const compile = wrapCompilerAsTypeGuard($compile);
// with special FromSchemaOptions
// (options need to be re-provided)
const compile = wrapCompilerAsTypeGuard<
FromSchemaOptions,
CompilingOptions,
ValidationOptions
>($compile);
```
## Frequently Asked Questions
- [Does `json-schema-to-ts` work on _.json_ file schemas?](./documentation/FAQs/does-json-schema-to-ts-work-on-json-file-schemas.md)
- [Will `json-schema-to-ts` impact the performances of my IDE/compiler?](./documentation/FAQs/will-json-schema-to-ts-impact-the-performances-of-my-ide-compiler.md)
- [I get a `type instantiation is excessively deep and potentially infinite` error, what should I do?](./documentation/FAQs/i-get-a-type-instantiation-is-excessively-deep-and-potentially-infinite-error-what-should-i-do.md)