Write a generic fetchJSON<T> wrapper and explain its type safety benefits
Tests preserving type info across async boundaries via generics. Outline: write fetchJSON<T> returning Promise<T>, note response.json() is any, and show T lets callers lock in the response shape for compile-time checks.
WHAT IT TESTS: Whether you can preserve type information through an async fetch wrapper using a generic instead of losing it to any. ANSWER OUTLINE: First, write fetchJSON<T>(url: string): Promise<T>. Second, note response.json() returns Promise<any>, erasing shape. Third, explain T lets the consumer declare the expected contract at the call site, so compiler enforces property access and catches mismatches before runtime. RED FLAG: Omitting <T> and returning Promise<any>, using type assertions, or believing generics add runtime validation.
Read the original → typescriptlang.org
- #typescript
- #generics
- #fetch
- #type-safety
- #promises
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.