<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Understanding Typescript Generics]]></title><description><![CDATA[Understanding Typescript Generics]]></description><link>https://typescript-blog.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 13:57:45 GMT</lastBuildDate><atom:link href="https://typescript-blog.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[# Understanding TypeScript Generics: Write Flexible, Reusable Code]]></title><description><![CDATA[When working with TypeScript, one of the most powerful features you’ll encounter is generics. If you've ever found yourself duplicating code just to handle…]]></description><link>https://typescript-blog.hashnode.dev/understanding-typescript-generics-write-flexible-reusable-code</link><guid isPermaLink="true">https://typescript-blog.hashnode.dev/understanding-typescript-generics-write-flexible-reusable-code</guid><dc:creator><![CDATA[Norman HategyekaMukama]]></dc:creator><pubDate>Tue, 17 Mar 2026 08:59:51 GMT</pubDate><content:encoded><![CDATA[<p>When working with TypeScript, one of the most powerful features you’ll encounter is <strong>generics</strong>. If you've ever found yourself duplicating code just to handle different data types, generics are the solution you’ve been looking for.</p>
<p>Let’s break it down in a practical and developer-friendly way.</p>
<h2>What Are Generics?</h2>
<p>Generics allow you to write code that works with <strong>multiple types</strong> instead of a single one. Think of them as placeholders for types.</p>
<p>Instead of saying:</p>
<blockquote>
<p>“This function only works with strings”</p>
</blockquote>
<p>You say:</p>
<blockquote>
<p>“This function works with any type—and I’ll decide that type later.”</p>
</blockquote>
<h2>Basic Example</h2>
<p>Without generics:</p>
<pre><code class="language-ts">function identity(value: string): string {
  return value
}
</code></pre>
<p>This only works with strings.</p>
<p>With generics:</p>
<pre><code class="language-ts">function identity&lt;T&gt;(value: T): T {
  return value
}
</code></pre>
<p>Now it works with <strong>any type</strong>:</p>
<pre><code class="language-ts">identity&lt;string&gt;("Hello")
identity&lt;number&gt;(42)
identity&lt;boolean&gt;(true)
</code></pre>
<hr />
<h2>Why Use Generics?</h2>
<h3>1. Reusability</h3>
<p>You write code once and use it with different types.</p>
<h3>2. Type Safety</h3>
<p>You still get full TypeScript type checking.</p>
<h3>3. Cleaner Code</h3>
<p>No need to create multiple versions of the same function.</p>
<hr />
<h2>Generics with Arrays</h2>
<pre><code class="language-ts">function getFirstItem&lt;T&gt;(arr: T[]): T {
  return arr[0]
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-ts">getFirstItem&lt;number&gt;([1, 2, 3])
getFirstItem&lt;string&gt;(["a", "b", "c"])
</code></pre>
<hr />
<h2>Generics in Interfaces</h2>
<pre><code class="language-ts">interface ApiResponse&lt;T&gt; {
  data: T
  status: number
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-ts">const userResponse: ApiResponse&lt;{ name: string }&gt; = {
  data: { name: "Norman" },
  status: 200
}
</code></pre>
<hr />
<h2>Generics in Classes</h2>
<pre><code class="language-ts">class Box&lt;T&gt; {
  content: T

  constructor(value: T) {
    this.content = value
  }
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-ts">const numberBox = new Box&lt;number&gt;(123)
const stringBox = new Box&lt;string&gt;("Hello")
</code></pre>
<hr />
<h2>Generic Constraints</h2>
<p>Sometimes you want to limit what types can be used.</p>
<pre><code class="language-ts">function printLength&lt;T extends { length: number }&gt;(item: T): void {
  console.log(item.length)
}
</code></pre>
<p>This ensures only types with a <code>length</code> property are allowed.</p>
<hr />
<h2>Multiple Generics</h2>
<pre><code class="language-ts">function pair&lt;K, V&gt;(key: K, value: V) {
  return { key, value }
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-ts">pair&lt;string, number&gt;("age", 25)
</code></pre>
<hr />
<h2>Default Generic Types</h2>
<pre><code class="language-ts">function createArray&lt;T = string&gt;(length: number, value: T): T[] {
  return Array(length).fill(value)
}
</code></pre>
<p>If no type is provided, it defaults to <code>string</code>.</p>
<hr />
<h2>Real-World Example (API Fetching)</h2>
<pre><code class="language-ts">async function fetchData&lt;T&gt;(url: string): Promise&lt;T&gt; {
  const response = await fetch(url)
  return response.json()
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-ts">type User = {
  id: number
  name: string
}

const user = await fetchData&lt;User&gt;("/api/user")
</code></pre>
<hr />
<h2>Common Mistakes</h2>
<h3>Overusing Generics</h3>
<p>Don’t use generics when a specific type is enough.</p>
<h3>Ignoring Type Inference</h3>
<p>TypeScript can often infer the type automatically:</p>
<pre><code class="language-ts">identity("Hello") // no need for &lt;string&gt;
</code></pre>
<hr />
<h2>When Should You Use Generics?</h2>
<p>Use generics when:</p>
<ul>
<li><p>You want reusable components/functions</p>
</li>
<li><p>You don’t know the type ahead of time</p>
</li>
<li><p>You want flexibility <strong>without losing type safety</strong></p>
</li>
</ul>
<hr />
<h2>Final Thoughts</h2>
<p>Generics are a game-changer in TypeScript. They help you write <strong>cleaner, reusable, and safer code</strong> especially in large-scale applications.</p>
]]></content:encoded></item></channel></rss>