API Type Inference Overview
Auto Type Generation
Backend β Frontend No manual work needed
Complete Inference
Parameters to responses All types guaranteed
Real-time Sync
On API changes Auto updates
IDE Support
Auto-completion Type hints
What is Type Inference?
Problem: Difficulty of Manual Type Definition
In traditional development, types for backend and frontend must be manually defined separately.- Duplicate work: Define same type twice in backend and frontend
- Sync missed: Frontend type update missed when backend changes
- Runtime errors: Type mismatch discovered only at runtime
- Hard to maintain: Management complexity increases with more types
Solution: Automatic Type Inference
Sonamu automatically infers backend types and passes them to frontend.- Backend types are automatically copied to frontend
- Automatically synced when API changes
- Single source of truth (backend is the only type source)
Type Inference Process
Step 1: Backend API Definition
Define API with TypeScript types.- Explicitly declare return types
- Nested objects, union types, literal types all supported
- All TypeScript type features available
Step 2: AST Parsing
Sonamu uses TypeScript Compiler API to analyze code.- Represents TypeScript code as tree structure
- Allows programmatic extraction of type information
- Obtains 100% accurate type information
Step 3: Service Type Generation
Insert extracted types into Service code.- Union types (
"admin" | "user") - Nested objects
- Array types
- Date, null, undefined and all TypeScript types
Step 4: TanStack Query Hook Generation
Types are accurately passed to React Hooks as well.Advanced Type Inference
Generic Types
APIs using generics are also accurately inferred.Subset System
Subset types are also automatically generated.- Return exact type based on Subset with
UserSubsetMapping[T] - Uses TypeScriptβs conditional types
Complex Nested Structures
Deeply nested types are also accurately inferred.Practical Usage
React Components
Types are automatically inferred with IDE support.- When typing
data.,user,statsare auto-suggested - When typing
data.user., all fields are auto-suggested - Immediate error display on wrong field access
Type Reuse
Generated types can be reused elsewhere.Form Data Types
API parameter types are also inferred.Type Safety Guarantees
1. Parameter Validation
Wrong parameters are detected at compile time.2. Response Type Guarantee
API response types are guaranteed.3. null/undefined Handling
Optional fields are accurately represented.Cautions
Next Steps
Compile-time Errors
API change detection
Shared Types
Type file structure
How Services Work
Understanding auto-generation
Using Services
Service usage