<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Generics on Commentary of Takao</title><link>https://takao.blog/en/tags/generics/</link><description>Recent content in Generics on Commentary of Takao</description><generator>Hugo -- gohugo.io</generator><language>en</language><copyright>Commentary of Takao</copyright><lastBuildDate>Sat, 13 Jun 2026 23:11:50 +0900</lastBuildDate><atom:link href="https://takao.blog/en/tags/generics/index.xml" rel="self" type="application/rss+xml"/><item><title>TypeScript Generic Constraints: Building Type-Safe APIs</title><link>https://takao.blog/en/web/typescript-generic-constraints/</link><pubDate>Tue, 05 Mar 2024 00:00:00 +0900</pubDate><guid>https://takao.blog/en/web/typescript-generic-constraints/</guid><description>&lt;img src="https://takao.blog/img/thumnail.webp" alt="Featured image of post TypeScript Generic Constraints: Building Type-Safe APIs" /&gt;&lt;p&gt;TypeScript generics let you write reusable, type-safe code, but without constraints they are too permissive. The &lt;code&gt;extends&lt;/code&gt; keyword restricts type parameters to shapes that have specific properties, giving you both flexibility and safety.&lt;/p&gt;
&lt;h2 id="the-extends-constraint"&gt;The extends Constraint
&lt;/h2&gt;&lt;p&gt;The foundation of generic constraints is the &lt;code&gt;extends&lt;/code&gt; keyword. It ensures a type parameter satisfies a required structure:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-gdscript3" data-lang="gdscript3"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;function getProperty&lt;span style="color:#f92672"&gt;&amp;lt;&lt;/span&gt;T, K &lt;span style="color:#66d9ef"&gt;extends&lt;/span&gt; keyof T&lt;span style="color:#f92672"&gt;&amp;gt;&lt;/span&gt;(obj: T, key: K): T[K] {
&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; &lt;span style="color:#66d9ef"&gt;return&lt;/span&gt; obj[key];
&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Here &lt;code&gt;K extends keyof T&lt;/code&gt; guarantees &lt;code&gt;key&lt;/code&gt; is a valid property of &lt;code&gt;obj&lt;/code&gt;. Attempting to pass an invalid key triggers a compile-time error. Common patterns include constraining to interfaces (&lt;code&gt;T extends { id: string }&lt;/code&gt;), union members, or primitive types.&lt;/p&gt;</description></item></channel></rss>