Web Development TypeScript Subjective
Oct 04, 2025

How do you implement compile-time validation of configuration objects?

Detailed Explanation
Use conditional types and mapped types to validate configuration structure at compile time. Basic Configuration Validation: type RequiredConfig = { apiUrl: string; timeout: number; retries: number; }; type ValidateConfig = { [K in keyof RequiredConfig]: K extends keyof T ? T[K] extends RequiredConfig[K] ? T[K] : never : never; }; function createClient(config: ValidateConfig) { // Implementation } // Usage createClient({ apiUrl: 'https://api.example.com', // OK timeout: 5000, // OK retries: 3 // OK }); // createClient({ apiUrl: 123 }); // Error: number not assignable to string Advanced Validation: type DeepValidate = { [K in keyof Schema]: K extends keyof T ? Schema[K] extends object ? T[K] extends object ? DeepValidate : never : T[K] extends Schema[K] ? T[K] : never : never; }; type DatabaseSchema = { host: string; port: number; credentials: { username: string; password: string; }; }; function connectDatabase(config: DeepValidate) { // Implementation } Benefits: • Catch configuration errors at compile time • Ensure required fields are provided • Validate nested object structures • Provide excellent IDE support.
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback