✅ Why use generics with arrays?
Generic arrays let you define what type of elements the array holds, ensuring type safety while keeping flexibility.
🔸 Syntax Options
const numbers: Array<number> = [1, 2, 3]; // Generic form
const names: string[] = ["Alice", "Bob"]; // Shorthand formBoth are valid — the first one is more explicitly generic.
🔸 Generic Function Working with Arrays
function getFirstElement<T>(arr: T[]): T {
return arr[0];
}
const firstNum = getFirstElement<number>([10, 20, 30]); // T = number
const firstStr = getFirstElement(["a", "b", "c"]); // T = string✅ Why use generics with promises?
Generics allow you to explicitly define the type a promise resolves to, helping TypeScript infer the correct return type after await or .then().
🔸 Example: Promise with a Generic Type
function fetchData<T>(url: string): Promise<T> {
return fetch(url).then(res => res.json());
}
// Define the expected type
interface User {
id: number;
name: string;
}
fetchData<User>("<https://api.example.com/user/1>")
.then(user => {
console.log(user.name); // user is of type User
});
}🔸 async/await with Generic Promises
async function getUser<T>(id: number): Promise<T> {
const res = await fetch(`/api/users/${id}`);
return await res.json();
}
interface Admin {
id: number;
role: string;
}
async function main() {
const admin = await getUser<Admin>(1);
console.log(admin.role);
}<div class="infographic-ts" id="infographic-ts">
<style>
.infographic-ts {
--body-font: system-ui, -apple-system, sans-serif;
--mono-font: ui-monospace, SFMono-Regular, Consolas, "Courier New", monospace;
--ed-bg: #1e1e1e;
--ed-bar: #2a2a2a;
--ed-out: #d4d4d4;
--ed-muted: #8a8a8a;
--ed-ok: #4ec9b0;
--run-bg: #2e7d46;
--run-bg-hover: #35924f;
--tok-kw: #c586c0;
--tok-type: #4ec9b0;
--tok-str: #ce9178;
--tok-num: #b5cea8;
--tok-punc: #d4d4d4;
--tok-cmt: #808080;
--tok-var: #ffffff;
max-width: 680px;
margin: 0 auto;
box-sizing: border-box;
background: transparent;
font-family: var(--body-font);
}
.infographic-ts * { box-sizing: border-box; }
.ts-header { font-family: 'Georgia', 'Fraunces', serif; font-weight: 700;
font-size: 1.9rem; letter-spacing: 0.01em; color: inherit; text-align: center;
margin: 0 0 1.4rem; }
.tabs { display: flex; justify-content: center; gap: 4px; margin-bottom: 1.1rem; flex-wrap: wrap; }
.tab-btn { font-family: var(--body-font); font-size: 0.82rem; font-weight: 500;
background: #ffffff; color: #2563eb; border: 1px solid #2563eb; padding: 0.65rem 1rem;
cursor: pointer; border-radius: 8px; }
.tab-btn.active { background: #2563eb; color: #ffffff; }
.tab-btn:hover:not(.active) { background: #eef3ff; }
.tab-panel { display: none; background: var(--ed-bg); border-radius: 8px;
padding: 1.1rem; }
.tab-panel.active { display: block; }
.code-window { background: var(--ed-bg); border: 1px solid #2f2f2f; border-radius: 8px;
overflow: hidden; margin-bottom: 1rem; }
.code-window:last-child { margin-bottom: 0; }
.code-topbar { display: flex; align-items: center; justify-content: space-between;
padding: 0.5rem 0.75rem; background: var(--ed-bar); }
.code-dots { display: flex; gap: 6px; }
.code-dot { width: 9px; height: 9px; border-radius: 50%; }
.code-dot.r { background: #ff5f57; }
.code-dot.y { background: #febc2e; }
.code-dot.g { background: #28c840; }
.code-filename { font-family: var(--mono-font); font-size: 0.74rem; color: var(--ed-muted); }
.run-btn { display: inline-flex; align-items: center; gap: 0.35rem; background: var(--run-bg);
color: #fff; border: none; border-radius: 4px; padding: 0.32rem 0.7rem; font-size: 0.74rem;
font-family: var(--body-font); font-weight: 500; cursor: pointer; }
.run-btn:hover { background: var(--run-bg-hover); }
.run-btn svg { width: 10px; height: 10px; }
.code-body { padding: 0.85rem 1.1rem; font-family: var(--mono-font); font-size: 0.8rem;
line-height: 1.65; color: var(--ed-out); white-space: pre; overflow-x: auto; }
.tok-kw { color: var(--tok-kw); }
.tok-type { color: var(--tok-type); }
.tok-str { color: var(--tok-str); }
.tok-num { color: var(--tok-num); }
.tok-punc { color: var(--tok-var); }
.tok-cmt { color: var(--tok-cmt); }
.tok-var { color: var(--tok-var); }
.console { padding: 0 1.1rem; max-height: 0; overflow: hidden; font-family: var(--mono-font);
font-size: 0.78rem; line-height: 1.65; transition: max-height 0.35s ease, padding 0.35s ease; }
.console.show { max-height: 260px; padding: 0 1.1rem 0.85rem; }
.console-line { color: var(--ed-out); }
.console-line.ok { color: var(--ed-ok); }
.note-line { font-family: var(--body-font); font-size: 0.8rem; color: var(--ed-muted);
padding: 0 0.2rem; margin: 0; }
</style>
<h2 class="ts-header">Generics with arrays & promises</h2>
<div class="tabs">
<button class="tab-btn active" data-tab="t1" type="button">Arrays</button>
<button class="tab-btn" data-tab="t2" type="button">Generic promise</button>
<button class="tab-btn" data-tab="t3" type="button">async/await</button>
</div>
<div class="tab-panel active" id="t1">
<div class="code-window">
<div class="code-topbar">
<div class="code-dots"><span class="code-dot r"></span><span class="code-dot y"></span><span class="code-dot g"></span></div>
<span class="code-filename">arrays.ts</span>
<button class="run-btn" id="arrBtn" type="button">
<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6 3 20 12 6 21 6 3"/></svg>
run
</button>
</div>
<div class="code-body"><span class="tok-kw">function</span> <span class="tok-var">getFirstElement</span><span class="tok-punc"><</span><span class="tok-type">T</span><span class="tok-punc">>(</span><span class="tok-var">arr</span><span class="tok-punc">:</span> <span class="tok-type">T</span><span class="tok-punc">[]):</span> <span class="tok-type">T</span> <span class="tok-punc">{</span>
<span class="tok-kw">return</span> <span class="tok-var">arr</span><span class="tok-punc">[</span><span class="tok-num">0</span><span class="tok-punc">];</span>
<span class="tok-punc">}</span>
<span class="tok-kw">const</span> <span class="tok-var">firstNum</span> <span class="tok-punc">=</span> <span class="tok-var">getFirstElement</span><span class="tok-punc"><</span><span class="tok-type">number</span><span class="tok-punc">>([</span><span class="tok-num">10</span><span class="tok-punc">,</span> <span class="tok-num">20</span><span class="tok-punc">,</span> <span class="tok-num">30</span><span class="tok-punc">]);</span>
<span class="tok-kw">const</span> <span class="tok-var">firstStr</span> <span class="tok-punc">=</span> <span class="tok-var">getFirstElement</span><span class="tok-punc">([</span><span class="tok-str">"a"</span><span class="tok-punc">,</span> <span class="tok-str">"b"</span><span class="tok-punc">,</span> <span class="tok-str">"c"</span><span class="tok-punc">]);</span>
<span class="tok-var">console</span><span class="tok-punc">.</span><span class="tok-var">log</span><span class="tok-punc">(</span><span class="tok-var">firstNum</span><span class="tok-punc">,</span> <span class="tok-var">firstStr</span><span class="tok-punc">);</span></div>
<div class="console" id="arrConsole"></div>
</div>
<p class="note-line">firstNum's T is given explicitly; firstStr's T is inferred from the array itself.</p>
</div>
<div class="tab-panel" id="t2">
<div class="code-window">
<div class="code-topbar">
<div class="code-dots"><span class="code-dot r"></span><span class="code-dot y"></span><span class="code-dot g"></span></div>
<span class="code-filename">fetch-data.ts</span>
<button class="run-btn" id="fetchBtn" type="button">
<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6 3 20 12 6 21 6 3"/></svg>
run
</button>
</div>
<div class="code-body"><span class="tok-kw">function</span> <span class="tok-var">fetchData</span><span class="tok-punc"><</span><span class="tok-type">T</span><span class="tok-punc">>(</span><span class="tok-var">url</span><span class="tok-punc">:</span> <span class="tok-type">string</span><span class="tok-punc">):</span> <span class="tok-type">Promise</span><span class="tok-punc"><</span><span class="tok-type">T</span><span class="tok-punc">></span> <span class="tok-punc">{</span>
<span class="tok-kw">return</span> <span class="tok-var">fetch</span><span class="tok-punc">(</span><span class="tok-var">url</span><span class="tok-punc">).</span><span class="tok-var">then</span><span class="tok-punc">(</span><span class="tok-var">res</span> <span class="tok-punc">=></span> <span class="tok-var">res</span><span class="tok-punc">.</span><span class="tok-var">json</span><span class="tok-punc">());</span>
<span class="tok-punc">}</span>
<span class="tok-kw">interface</span> <span class="tok-type">User</span> <span class="tok-punc">{</span>
<span class="tok-var">id</span><span class="tok-punc">:</span> <span class="tok-type">number</span><span class="tok-punc">;</span>
<span class="tok-var">name</span><span class="tok-punc">:</span> <span class="tok-type">string</span><span class="tok-punc">;</span>
<span class="tok-punc">}</span>
<span class="tok-var">fetchData</span><span class="tok-punc"><</span><span class="tok-type">User</span><span class="tok-punc">>(</span><span class="tok-str">"https://api.example.com/user/1"</span><span class="tok-punc">)</span>
<span class="tok-punc">.</span><span class="tok-var">then</span><span class="tok-punc">(</span><span class="tok-var">user</span> <span class="tok-punc">=></span> <span class="tok-punc">{</span>
<span class="tok-var">console</span><span class="tok-punc">.</span><span class="tok-var">log</span><span class="tok-punc">(</span><span class="tok-var">user</span><span class="tok-punc">.</span><span class="tok-var">name</span><span class="tok-punc">);</span>
<span class="tok-punc">});</span></div>
<div class="console" id="fetchConsole"></div>
</div>
<p class="note-line">Promise<T> carries T through .then() — user is typed as User, not unknown. (Network simulated here.)</p>
</div>
<div class="tab-panel" id="t3">
<div class="code-window">
<div class="code-topbar">
<div class="code-dots"><span class="code-dot r"></span><span class="code-dot y"></span><span class="code-dot g"></span></div>
<span class="code-filename">async-await.ts</span>
<button class="run-btn" id="asyncBtn" type="button">
<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="6 3 20 12 6 21 6 3"/></svg>
run
</button>
</div>
<div class="code-body"><span class="tok-kw">async function</span> <span class="tok-var">getUser</span><span class="tok-punc"><</span><span class="tok-type">T</span><span class="tok-punc">>(</span><span class="tok-var">id</span><span class="tok-punc">:</span> <span class="tok-type">number</span><span class="tok-punc">):</span> <span class="tok-type">Promise</span><span class="tok-punc"><</span><span class="tok-type">T</span><span class="tok-punc">></span> <span class="tok-punc">{</span>
<span class="tok-kw">const</span> <span class="tok-var">res</span> <span class="tok-punc">=</span> <span class="tok-kw">await</span> <span class="tok-var">fetch</span><span class="tok-punc">(</span><span class="tok-str">`/api/users/${</span><span class="tok-var">id</span><span class="tok-str">}`</span><span class="tok-punc">);</span>
<span class="tok-kw">return</span> <span class="tok-kw">await</span> <span class="tok-var">res</span><span class="tok-punc">.</span><span class="tok-var">json</span><span class="tok-punc">();</span>
<span class="tok-punc">}</span>
<span class="tok-kw">interface</span> <span class="tok-type">Admin</span> <span class="tok-punc">{</span>
<span class="tok-var">id</span><span class="tok-punc">:</span> <span class="tok-type">number</span><span class="tok-punc">;</span>
<span class="tok-var">role</span><span class="tok-punc">:</span> <span class="tok-type">string</span><span class="tok-punc">;</span>
<span class="tok-punc">}</span>
<span class="tok-kw">async function</span> <span class="tok-var">main</span><span class="tok-punc">()</span> <span class="tok-punc">{</span>
<span class="tok-kw">const</span> <span class="tok-var">admin</span> <span class="tok-punc">=</span> <span class="tok-kw">await</span> <span class="tok-var">getUser</span><span class="tok-punc"><</span><span class="tok-type">Admin</span><span class="tok-punc">>(</span><span class="tok-num">1</span><span class="tok-punc">);</span>
<span class="tok-var">console</span><span class="tok-punc">.</span><span class="tok-var">log</span><span class="tok-punc">(</span><span class="tok-var">admin</span><span class="tok-punc">.</span><span class="tok-var">role</span><span class="tok-punc">);</span>
<span class="tok-punc">}</span>
<span class="tok-var">main</span><span class="tok-punc">();</span></div>
<div class="console" id="asyncConsole"></div>
</div>
<p class="note-line">await unwraps Promise<T> back down to T — admin.role is safe without any extra checks. (Network simulated here.)</p>
</div>
<script>
(function () {
var wrapper = document.currentScript.closest('.infographic-ts')
|| document.querySelector('.infographic-ts');
var root = wrapper;
var tabBtns = root.querySelectorAll('.tab-btn');
var panels = root.querySelectorAll('.tab-panel');
tabBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
var target = btn.getAttribute('data-tab');
tabBtns.forEach(function (b) { b.classList.toggle('active', b === btn); });
panels.forEach(function (p) { p.classList.toggle('active', p.id === target); });
});
});
function line(consoleEl, cls, text) {
var el = document.createElement('div');
el.className = 'console-line ' + (cls || '');
el.textContent = text;
consoleEl.appendChild(el);
}
function bind(id, consoleId, cb) {
var btn = root.querySelector('#' + id);
var c = root.querySelector('#' + consoleId);
btn.addEventListener('click', function () {
c.innerHTML = '';
c.classList.add('show');
cb(c);
setTimeout(function () {
c.scrollIntoView({ behavior: 'smooth', block: 'end' });
}, 50);
});
}
bind('arrBtn', 'arrConsole', function (c) {
line(c, 'ok', '10 a');
});
bind('fetchBtn', 'fetchConsole', function (c) {
line(c, '', 'fetching user/1\u2026');
setTimeout(function () {
line(c, 'ok', 'Tisha');
}, 500);
});
bind('asyncBtn', 'asyncConsole', function (c) {
line(c, '', 'fetching /api/users/1\u2026');
setTimeout(function () {
line(c, 'ok', 'admin');
}, 500);
});
})();
</script>
</div>🧠 Summary
Feature | Example |
|---|---|
Generic Array |
|
Function with array |
|
Generic Promise |
|
| Strongly typed API responses |