File tree 2 files changed +58
-1
lines changed
2 files changed +58
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1232 TILs and counting..._
13
+ _ 1233 TILs and counting..._
14
14
15
15
---
16
16
@@ -1136,6 +1136,7 @@ _1232 TILs and counting..._
1136
1136
- [ Compiler Checks For Unused Params And Variables] ( typescript/compiler-checks-for-unused-params-and-variables.md )
1137
1137
- [ Extract Object Type Keys Into A Union Type] ( typescript/extract-object-type-keys-into-a-union-type.md )
1138
1138
- [ Extract Object Type Values Into A Union Type] ( typescript/extract-object-type-values-into-a-union-type.md )
1139
+ - [ Generate Inferred Type From Zod Schema] ( typescript/generate-inferred-type-from-zod-schema.md )
1139
1140
- [ Interfaces With The Same Name Are Merged] ( typescript/interfaces-with-the-same-name-are-merged.md )
1140
1141
- [ Re-Export An Imported Type] ( typescript/re-export-an-imported-type.md )
1141
1142
- [ Type Narrowing With Similarly Shaped Objects] ( typescript/type-narrowing-with-similarly-shaped-objects.md )
Original file line number Diff line number Diff line change
1
+ # Generate Inferred Type From Zod Schema
2
+
3
+ One of the killer features of [ ` Zod ` ] ( https://github.com/colinhacks/zod ) is
4
+ that it does double-duty. When you define a schema, you can use that for
5
+ runtime checks. You can also generate an inferred type from that schema for
6
+ static type checking.
7
+
8
+ Let's say I have the following schema defined for data representing a
9
+ _ contact_ .
10
+
11
+ ``` typescript
12
+ import {z } from ' zod'
13
+
14
+ const contactSchema = z .object ({
15
+ person: z .object ({
16
+ firstName: z .string (),
17
+ lastName: z .string ()
18
+ }),
19
+ email: z .string ().email (),
20
+ })
21
+ ```
22
+
23
+ I can use this schema along with Zod's
24
+ [ ` z.infer() ` ] ( https://github.com/colinhacks/zod#type-inference ) function to
25
+ generate a type that I can use throughout my codebase.
26
+
27
+ ``` typescript
28
+ const createContact = (data : z .infer <typeof contactSchema >) => {
29
+ // ...
30
+ }
31
+ ```
32
+
33
+ If I inspect data, I can see that I get an object type generated from the
34
+ ` contactSchema ` .
35
+
36
+ ``` typescript
37
+ /* data: {
38
+ * person: {
39
+ * firstName: string;
40
+ * lastName: string;
41
+ * };
42
+ * email: string;
43
+ * }
44
+ */
45
+ ```
46
+
47
+ That works, but looks a bit cluttered. I could pull it out into a defined type.
48
+ One that could even be exported if I was so inclined.
49
+
50
+ ``` typescript
51
+ export type Contact = z .infer <typeof contactSchema >
52
+
53
+ const createContact = (data : Contact ) => {
54
+ // ...
55
+ }
56
+ ```
You can’t perform that action at this time.
0 commit comments