Commit 84e9526 1 parent 3020638 commit 84e9526 Copy full SHA for 84e9526
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 @@ -675,6 +675,30 @@ type User = z.infer<typeof User>;
675
675
// User: { username: string }
676
676
```
677
677
678
+ Validating an API response:
679
+
680
+ ``` ts
681
+ import { z } from " zod" ;
682
+
683
+ const userSchema = z .object ({
684
+ id: z .number (),
685
+ username: z .string (),
686
+ email: z .string ().email (),
687
+ });
688
+
689
+ type User = z .infer <typeof userSchema >;
690
+
691
+ async function getUserById(id : number ) {
692
+ const response = await fetch (` /api/users/${id } ` );
693
+ // data is untyped JSON response from the API
694
+ const data = await response .json ();
695
+
696
+ // parse and validate the data against the schema to ensure it matches the expected shape
697
+ const user = userSchema .parse (data );
698
+
699
+ // user is now fully typed as { id: number, username: string, email: string }
700
+ return user ;
701
+ }
678
702
```
679
703
680
704
## Primitives
You can’t perform that action at this time.
0 commit comments