
JSON to TypeScript Interface: Complete Guide with Zod and Type Guards
Generate TypeScript interfaces from JSON safely. Here's how to do it right. Interface vs Type Alias // Interface — preferred for JSON object shapes interface User { id : number ; name : string ; email : string ; active : boolean ; } // Type alias — better for unions and computed types type UserId = number ; type Status = ' active ' | ' inactive ' | ' pending ' ; type UserOrAdmin = User | AdminUser ; Optional Properties interface User { id : number ; name : string ; email : string ; bio ?: string ; // optional — may be absent avatarUrl ?: string ; // optional — may be absent } // Index signatures for dynamic keys interface Metadata { [ key : string ]: string | number | boolean ; } Union Types for Mixed Values // JSON value type type JsonValue = | string | number | boolean | null | JsonValue [] | { [ key : string ]: JsonValue }; // Discriminated union (tagged union) type ApiResponse = | { status : ' success ' ; data : User } | { status : ' error ' ; message : string ; code : number }; //
Continue reading on Dev.to JavaScript
Opens in a new tab

