Commit b6c623e 1 parent 207205c commit b6c623e Copy full SHA for b6c623e
File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -661,6 +661,32 @@ type User = z.infer<typeof User>;
661
661
// { username: string }
662
662
```
663
663
664
+ Validating an API response:
665
+
666
+ ``` ts
667
+ import { z } from " zod" ;
668
+
669
+ const userSchema = z .object ({
670
+ id: z .number (),
671
+ username: z .string (),
672
+ email: z .string ().email (),
673
+ });
674
+
675
+ type User = z .infer <typeof userSchema >;
676
+
677
+ async function getUserById(id : number ) {
678
+ const response = await fetch (` /api/users/${id } ` );
679
+ // data is untyped JSON response from the API
680
+ const data = await response .json ();
681
+
682
+ // parse and validate the data against the schema to ensure it matches the expected shape
683
+ const user = userSchema .parse (data );
684
+
685
+ // user is now fully typed as { id: number, username: string, email: string }
686
+ return user ;
687
+ }
688
+ ```
689
+
664
690
## Primitives
665
691
666
692
``` ts
You can’t perform that action at this time.
0 commit comments