TypeScript decision: How should a function that calls fetch be typed
TypeScript decision: How should a function that calls fetch be typed?
Options:
1. Type the return statement
2. Type the function's signature
3. Type both
Poll in the next tweet 👇
#typescript

Poll: How should a function that calls fetch be typed?
#typescript
Each option has benefits:
1. Typing the return casts on the exact line where it’s needed, which is intuitive. You don’t have to specify Promise. It’s inferred.
2. Typed signatures are more scannable.
3. Both is like double-entry book keeping. It specifies intent in 2 spots.
Another benefit to 2: Typing the func signature assures that if other return paths are added later, all paths return the same type.
Many people said “validate the response with Zod/io-ts/etc.”
Yes, Zod is useful. But, it’s a tradeoff. Runtime validation has a bundle cost, and runtime cost.
If I control the backend, I control the response shape. In that case, runtime validation on every fetch feels needless.