← Back to Emergency Home

Understanding TypeScript Generics

2024-03-10

Generics start as a small syntax change—angle brackets around a type parameter—but they unlock reusable, type-safe abstractions. <div class="shiki-wrapper" data-lang="ts" data-raw="ZnVuY3Rpb24gdXNlRmV0Y2g8VERhdGE+KHVybDogc3RyaW5nKTogUHJvbWlzZTxURGF0YT4gewogIC8vIC4uLmltcGxlbWVudGF0aW9uCn0="><pre class="shiki night-owl" style="background-color:#011627;color:#d6deeb" tabindex="0"><code><span class="line"><span style="color:#C792EA">function</span><span style="color:#82AAFF;font-style:italic"> useFetch</span><span style="color:#D6DEEB">&#x3C;</span><span style="color:#FFCB8B">TData</span><span style="color:#D6DEEB">></span><span style="color:#D9F5DD">(</span><span style="color:#D7DBE0">url</span><span style="color:#7FDBCA">:</span><span style="color:#C5E478"> string</span><span style="color:#D9F5DD">)</span><span style="color:#7FDBCA">:</span><span style="color:#FFCB8B"> Promise</span><span style="color:#D6DEEB">&#x3C;</span><span style="color:#FFCB8B">TData</span><span style="color:#D6DEEB">> {</span></span> <span class="line"><span style="color:#637777;font-style:italic"> // ...implementation</span></span> <span class="line"><span style="color:#D6DEEB">}</span></span></code></pre></div> The `TData` placeholder lets you tell TypeScript what you expect back. Consumers get autocomplete, error reporting, and refactoring help for free. ## Patterns to try - Generic React components with discriminated unions. - Utility types for state machines. - API clients that infer response payloads. Generics are not scary. Start by adding them to helper functions, then graduate to components and hooks.

© 2026 Karthik. Rendered natively via HTML.