๐ง๐๐ฝ๐ฒ-๐ฆ๐ฎ๐ณ๐ฒ ๐๐ฃ๐ ๐๐น๐ถ๐ฒ๐ป๐๐ ๐ช๐ถ๐๐ต๐ผ๐๐ ๐๐ผ๐ฑ๐ฒ๐ด๐ฒ๐ป
Stop using as User for API responses.
The as User cast is a lie you tell your compiler. TypeScript thinks the data is correct. At runtime, the data is often wrong. Bugs surface three functions later. The stack trace does not help.
The network is where you trust nothing. Verify data at the boundary.
Use Zod. Define a schema once. Zod gives you the type and the check. Your types will not drift.
Build a simple fetch wrapper. Pass a schema into it. Use safeParse to check the body. Data becomes a type only after the check.
Do not throw errors. Return a Result object. Use a union with ok: true or ok: false. This forces you to handle failures.
Apply the same logic to your URLs. Schema your query parameters. Prevent typos before the request leaves.
Use Zod when:
- You have few endpoints.
- You have no OpenAPI spec.
- You want runtime safety.
Use codegen when:
- You have hundreds of endpoints.
- You have a perfect spec.
A cast is not a check. Treat as User as a code smell near fetch.
Parse at the boundary. Trust inside.
Source: https://dev.to/pavelespitia/type-safe-api-clients-in-typescript-without-a-code-generator-1k32