How I use Zod with Wordle Unlimited
Type safety matters whenever data goes over the network, lives in localStorage, or sits anywhere else we don't fully control.
Let's say we built a strictly typed way to store data in localStorage:
We have no control over what happens to the data, so it sits outside our type system. A user can open their developer tools and alter it. Once that happens, there's no guarantee the data still satisfies the Colors type.
We have types, but that's not the same as having type safety.
A quick intro into Zod
Zod validates data in TypeScript applications. It enforces precise data structures, making sure incoming data matches the expected types and shapes. For more, see How to validate data using Zod
A quick intro to Wordle Unlimited
Wordle Unlimited is a guessing game with 6 tries. After each guess, the tile colors change to show how close your guess was to the word. Each guess must be a valid word with the same number of letters as the squares in a row.
Example:
We want to save game progress in the browser localStorage while type-checking the stored values. This guards against game-breaking issues if those values are altered.
Validation with Zod
The schema defines 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:
To get the data back, we use safeParse. It returns an object with either the parsed data or a ZodError instance holding detailed validation information:
This lets us use Zod to validate external data that falls outside our type system.
Quick Recap
-
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
safeParsefor graceful error handling - Leverage
z.inferfor type inference - Create reusable schemas for common patterns
-
Real-World Applications
- Form validation
- API response validation
- Local storage data validation
- Configuration validation