How I use Zod with Wordle Unlimited
When dealing with data that goes over the network or stored in localStorage
or any other place where we don't have full control over it, type safety becomes crucial.
Let's say we built a strictly typed way to store data in localStorage:
Since we have no control over what happens to the data, it is outside of our type system. A user might go into their developer tools and alter the data. At this point, our data went outside of the type system and now there is no guarantee that the data still satisfies the Colors
type.
What we have done now, is having types and it is not the same as having type safety!
A quick intro into Zod
Zod is used for data validation in TypeScript applications. The primary goal is to enforce precise data structures, ensuring that incoming data conforms to expected types and shapes. For more information refer to How to validate data using Zod
A quick intro to Wordle Unlimited
Wordle Unlimited is a guessing game consisting of 6 tries after each guess the color of the tiles will change to how close your guess was to the word. Each guess must be a valid word with the same number of letters as the number of squares horizontally.
Example:
We aim to save the game progress in the browser localStorage
while ensuring type checks on stored values. This will play a role in safeguards against potential game-breaking issues if values are altered.
Validation with Zod
The schema represents the structure and validation rules for the Wordle data type:
To avoid code duplication we can extract the TypeScript type of GameSchema
using z.infer
:
Now to get the data back we can use safeParse
. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation:
This way enables us to utilize Zod for validating external data that falls outside our type system.
Key Takeaways
-
Type Safety Beyond TypeScript
- TypeScript types only exist at compile time
- Runtime validation is crucial for external data
- Zod bridges the gap between compile-time and runtime type safety
-
Data Validation Best Practices
- Always validate external data sources
- Use
safeParse
for graceful error handling - Leverage
z.infer
for type inference - Create reusable schemas for common patterns
-
Real-World Applications
- Form validation
- API response validation
- Local storage data validation
- Configuration validation
References
Let's work together
I build exceptional and accessible digital experiences for the web
WRITE AN EMAILor reach out directly at hello@mohammadshehadeh.com