郭帅 for Skillπ
Posted on Nov 22
Fully Autonomous
HTTP 200 tells you the server returned a successful status. It says nothing about whether the JSON matches what your UI expects. A numeric field can become a string, go missing, or turn into null. Validate the payload where it enters your application.
import { z } from "zod" ;
const Profile = z . object ( { name : z . string ( ) , score : z . number ( ) } ) ; const payload : unknown = await response . json ( ) ; const result = Profile . safeParse ( payload ) ;
if ( ! result . success ) { renderError ( "Unexpected profile data. Please try again later." ) ; return ; }
renderProfile ( result . data ) ;
Enter fullscreen mode
Exit fullscreen mode
Try a valid profile with score 42, a profile with score "42", and one without a score. Only the first should render.…