TypeScript: Avoid Optional Properties with Strict Interfaces

🛑 Stop making all your TypeScript interface properties optional. If you use TypeScript, you have probably been tempted to just slap a ? on a property to make the compiler stop yelling at you. id?: string; name?: string; We do this because a User in the database has an id, but a User being submitted in a registration form doesn't have an id yet. So we make it optional to share the same interface. This is a massive trap. 🪤 When you make properties optional, you are destroying your type safety. You will spend the rest of your app writing defensive code: if (user.id !== undefined) { ... }. The Fix: Strict Base Interfaces + Utility Types. ✨ Define your core interface as the absolute, strict truth (no optional fields unless they are truly optional). Then, let TypeScript do the heavy lifting using Omit and Pick. Why this wins: ✅ Zero Guesswork: If a function requires a UserCardProps, you know with 100% certainty that name and email will be there. No undefined checks needed. ✅ Single Source of Truth: If you add a new required property to your base User, your derived utility types automatically inherit it. ✅ Self-Documenting: Reading Omit<User, 'id'> instantly tells the next developer exactly what this object is meant for. Stop fighting the TypeScript compiler. Let Utility Types do the work for you. 🧠 Are you using Pick and Omit, or are you still living in the Optional wild west? 👇 #TypeScript #JavaScript #WebDevelopment #Frontend #ReactJS #CleanCode #SoftwareEngineering

  • A split-screen TypeScript code comparison. The top red section, labeled 'The Optional Trap', shows a User interface where every property has a question mark, making them optional and defeating type safety. The bottom green section, labeled 'Utility Types', shows a strict base User interface, and uses TypeScript's Omit and Pick utility types to create safe, predictable variations for creating users and displaying UI cards.

Pro Tip: Is there ever a good time to make everything optional? Yes! If you are building a PATCH endpoint for updating a user, you can use the built-in Partial<User> utility type. It automatically makes every property from your strict base interface optional, but only for that specific update payload. It's magic. 🪄

Like
Reply

To view or add a comment, sign in

Explore content categories