Commit d8d20a6 1 parent 700d9f4 commit d8d20a6 Copy full SHA for d8d20a6
File tree 1 file changed +24
-0
lines changed
1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -708,6 +708,30 @@ type User = z.infer<typeof User>;
708
708
// User: { username: string }
709
709
```
710
710
711
+ Validating an API response:
712
+
713
+ ``` ts
714
+ import { z } from " zod" ;
715
+
716
+ const userSchema = z .object ({
717
+ id: z .number (),
718
+ username: z .string (),
719
+ email: z .string ().email (),
720
+ });
721
+
722
+ type User = z .infer <typeof userSchema >;
723
+
724
+ async function getUserById(id : number ) {
725
+ const response = await fetch (` /api/users/${id } ` );
726
+ // data is untyped JSON response from the API
727
+ const data = await response .json ();
728
+
729
+ // parse and validate the data against the schema to ensure it matches the expected shape
730
+ const user = userSchema .parse (data );
731
+
732
+ // user is now fully typed as { id: number, username: string, email: string }
733
+ return user ;
734
+ }
711
735
```
712
736
713
737
## Primitives
You can’t perform that action at this time.
0 commit comments