DEV Community

Aleksei Aleinikov
Aleksei Aleinikov

Posted on

๐ŸŽฏ Exactly One. Never Zero. Never Two.

Ever built a function that should accept one of several options โ€” but not more, not less?

In 2025, TypeScript makes it cleaner than ever with a pattern called RequireOnlyOne. One small generic gives you:
โœ… Precise API contracts
โŒ No runtime ambiguity
๐Ÿ’ฅ Compile-time enforcement
๐Ÿ” Use cases:
โ€ข A weather API: cityId or coordinates
โ€ข A React Avatar: initials or photo URL
โ€ข An invoice handler: invoiceId or subscriptionId

๐Ÿง  Bonus insight: works great with OpenAPI, and easy to adapt into RequireAtLeastOne.

Skip the boilerplate, prevent misuse, and make future refactors effortless.

๐Ÿ‘ Like real-world TS tips? Follow for more clean patterns, no fluff.
https://levelup.gitconnected.com/requireonlyone-in-2025-typescript-trick-for-exactly-one-property-8637ca5e6907

Top comments (0)