Programming languages · Intermediate · 25 min
Write reusable TypeScript with generics
By Padding · Updated 18 Nov 2026
Node.js 26.13 · TypeScript 7.0.2 (node:26 image)
You will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
On this page
Most codebases have a family of functions that differ only in the type they handle: findUser, findOrder, findProduct, each a copy of the last with a word changed. Generics let you write the function once and keep the types. The compiler still knows that looking up a user gives you a User, and it still stops you passing the wrong thing.
In this tutorial you start from exactly that duplication and remove it. Along the way you use type parameters and inference, constraints with extends, keyof and indexed access types, default type parameters, generic interfaces and a mapped type you write yourself. You also see where generics make code worse. You finish with a fetchJson<T> helper that checks what the server sent, and tests for it that run with the Node.js test runner.
Everything runs with tsc and node, with no framework. Every check uses the compiler itself: some files contain lines that are meant to fail, marked so that tsc fails if they do not.
Step 1 · Set up the project
Create a throwaway project with TypeScript 7.0.2 and the Node.js 26 type definitions. The TypeScript 7 setup tutorial explains each setting in this tsconfig.json. The important one here is strict, because generics are only as useful as the checks around them:
mkdir -p ~/generics-demo/src
cd ~/generics-demo
npm init -y > /dev/null
npm pkg set type=module
npm install --save-dev typescript@7.0.2 @types/node@26.6.11
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"moduleResolution": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npx tsc --versionCheck it worked
npx tsc --version prints Version 7.0.2. Your folder has package.json, package-lock.json, tsconfig.json, node_modules and an empty src.
Step 2 · Start from three copies of one function
Create the types and some sample data. The data stands in for whatever your app loads from a database or an API:
cd ~/generics-demo
cat > src/models.ts <<'TS'
export interface User {
id: string;
name: string;
email: string;
}
export interface Order {
id: string;
userId: string;
total: number;
currency: "NGN" | "KES" | "GHS" | "USD";
}
export interface Product {
id: string;
title: string;
stock: number;
}
TS
cat > src/data.ts <<'TS'
import type { Order, Product, User } from "./models.js";
export const users: User[] = [
{ id: "u1", name: "Amara Okafor", email: "amara@example.com" },
{ id: "u2", name: "Kwame Mensah", email: "kwame@example.com" },
];
export const orders: Order[] = [
{ id: "o1", userId: "u1", total: 12500, currency: "NGN" },
{ id: "o2", userId: "u2", total: 340, currency: "GHS" },
];
export const products: Product[] = [
{ id: "p1", title: "Solar lamp", stock: 40 },
{ id: "p2", title: "Phone charger", stock: 0 },
];
TSNow write the code you are going to replace. These three functions are the same loop with a different type in the signature:
cd ~/generics-demo
cat > src/copies.ts <<'TS'
import type { Order, Product, User } from "./models.js";
export function findUser(items: User[], id: string): User | undefined {
for (const item of items) {
if (item.id === id) return item;
}
return undefined;
}
export function findOrder(items: Order[], id: string): Order | undefined {
for (const item of items) {
if (item.id === id) return item;
}
return undefined;
}
export function findProduct(items: Product[], id: string): Product | undefined {
for (const item of items) {
if (item.id === id) return item;
}
return undefined;
}
TS
cat > src/main.ts <<'TS'
import { orders, products, users } from "./data.js";
import { findOrder, findProduct, findUser } from "./copies.js";
console.log(findUser(users, "u1")?.name);
console.log(findOrder(orders, "o1")?.total);
console.log(findProduct(products, "p1")?.title);
TS
npx tsc
node dist/main.jsA fix to one copy, such as a faster lookup, has to be made three times, and a fourth type means a fourth copy. You could write one function that takes any[], but then every caller gets any back and the compiler stops checking.
Check it worked
The program prints three lines: Amara Okafor, 12500 and Solar lamp.
Step 3 · Write one generic function with a constraint
A type parameter is a placeholder for a type, written in angle brackets after the function name. Start with the smallest possible generic function, then try the lookup without telling the compiler anything about T:
cd ~/generics-demo
cat > src/loose.ts <<'TS'
export function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
export function findLoose<T>(items: readonly T[], id: string): T | undefined {
return items.find((item) => item.id === id);
}
TS
npx tsc --noEmit || echo "tsc exited with status $?"first compiles. Whatever type of array you pass, T becomes that element type, and the return type follows. findLoose does not: the compiler reports Property 'id' does not exist on type 'T', because T could be any type at all, including number.
A constraint fixes that. T extends { id: string } means "any type, as long as it has a string id". Inside the function you may use item.id, and callers can only pass arrays of things with an id:
cd ~/generics-demo
rm src/loose.ts
cat > src/generics.ts <<'TS'
export function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
export function findById<T extends { id: string }>(
items: readonly T[],
id: string,
): T | undefined {
return items.find((item) => item.id === id);
}
TS
cat > src/main.ts <<'TS'
import { orders, products, users } from "./data.js";
import { findById } from "./generics.js";
console.log(findById(users, "u1")?.name);
console.log(findById(orders, "o1")?.total);
console.log(findById(products, "p1")?.title);
TS
rm src/copies.ts
npx tsc
node dist/main.jsYou never wrote findById<User>(...). TypeScript infers T from the argument: users is User[], so T is User and the result is User | undefined. In an editor with TypeScript support, hover over findById in main.ts to see the inferred type. You can still pass the type argument yourself, for example findById<Product>(products, "p1"), when inference picks something too wide.
Now prove the compiler still protects you. A // @ts-expect-error comment tells tsc that the next line must fail to type-check. If the line compiles, tsc reports the comment itself as an error, so each one is a small test of your types:
cd ~/generics-demo
cat > src/checks.ts <<'TS'
import { orders, users } from "./data.js";
import { first, findById } from "./generics.js";
import type { Order, User } from "./models.js";
const firstOrder: Order | undefined = first(orders);
const user: User | undefined = findById(users, "u1");
// @ts-expect-error a User is not an Order
const wrong: Order | undefined = findById(users, "u1");
// @ts-expect-error numbers have no id, so they break the constraint
findById([1, 2, 3], "1");
export { firstOrder, user, wrong };
TS
npx tsc --noEmitCheck it worked
node dist/main.js prints the same three lines as before, from one function. npx tsc --noEmit prints nothing. To see a check do its job, delete the // @ts-expect-error line above findById([1, 2, 3], "1") and run npx tsc --noEmit again: it reports Type 'number' is not assignable to type '{ id: string; }' for each element of the array. Put the comment back before you continue.
Step 4 · Pick properties safely with keyof and T[K]
A common helper takes a list of records and returns one field from each, a pluck. Written with strings, it loses the types. Written with keyof and an indexed access type, it keeps them:
keyof Tis the union of a type's property names. ForOrderit is"id" | "userId" | "total" | "currency".T[K]is the type of propertyKofT.Order["total"]isnumber.
Add pluck to src/generics.ts. The second type parameter K is constrained to the keys of the first:
cd ~/generics-demo
cat >> src/generics.ts <<'TS'
export function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
TS
cat > src/checks-pluck.ts <<'TS'
import { orders, users } from "./data.js";
import { pluck } from "./generics.js";
import type { Order } from "./models.js";
const totals: number[] = pluck(orders, "total");
const currencies: Order["currency"][] = pluck(orders, "currency");
// @ts-expect-error "nmae" is not a key of User
pluck(users, "nmae");
// @ts-expect-error totals are numbers, not strings
const asText: string[] = pluck(orders, "total");
export { totals, currencies, asText };
TS
npx tsc --noEmitK is inferred as the literal "total", not string, so T[K] is exactly number. currencies comes back as the union "NGN" | "KES" | "GHS" | "USD", not as string.
Check it worked
npx tsc --noEmit prints nothing. In your editor, type pluck(users, "") and put the cursor between the quotes: autocomplete offers id, name and email, because the compiler knows the allowed keys.
Step 5 · Describe API results with generic interfaces and defaults
Interfaces and type aliases take type parameters too. A Result<T> says "this either worked and holds a T, or failed and holds an error". Give the error type a default, E = string, so the common case is short to write:
cd ~/generics-demo
cat > src/result.ts <<'TS'
export interface Ok<T> {
readonly ok: true;
readonly value: T;
}
export interface Fail<E> {
readonly ok: false;
readonly error: E;
}
export type Result<T, E = string> = Ok<T> | Fail<E>;
export function ok<T>(value: T): Ok<T> {
return { ok: true, value };
}
export function fail<E>(error: E): Fail<E> {
return { ok: false, error };
}
TS
cat > src/checks-result.ts <<'TS'
import { users } from "./data.js";
import { findById } from "./generics.js";
import type { User } from "./models.js";
import { fail, ok, type Result } from "./result.js";
function lookUp(id: string): Result<User> {
const user = findById(users, id);
return user ? ok(user) : fail(`No user with id ${id}`);
}
interface HttpProblem {
status: number;
message: string;
}
const custom: Result<User, HttpProblem> = fail({ status: 404, message: "Not Found" });
const found = lookUp("u1");
if (found.ok) {
const name: string = found.value.name;
console.log(name);
} else {
const message: string = found.error;
console.log(message);
}
// @ts-expect-error the default error type is string, not number
const badError: Result<User> = fail(500);
export { custom, badError };
TS
npx tsc --noEmitResult<User> is Result<User, string> because of the default. Result<User, HttpProblem> overrides it. Checking found.ok tells the compiler which half of the union you have, so found.value is only available after the check. That technique has its own tutorial: narrow types safely with discriminated unions.
Check it worked
npx tsc --noEmit prints nothing. Move the line const name: string = found.value.name; above the if and run it again: the compiler reports that property value does not exist on type Fail<string>. Move it back.
Step 6 · Build a mapped type by hand
An update form usually sends only the fields that changed. You want a type that is "the same object, with every property optional". TypeScript ships this as Partial<T>, but writing it yourself shows how mapped types work. [K in keyof T] loops over the property names of T, the ? makes each optional, and T[K] keeps each property's type:
cd ~/generics-demo
cat > src/patch.ts <<'TS'
export type Patch<T> = { [K in keyof T]?: T[K] };
export type Frozen<T> = { readonly [K in keyof T]: T[K] };
export function applyPatch<T extends object>(item: T, patch: Patch<T>): T {
return { ...item, ...patch };
}
TS
cat > src/checks-patch.ts <<'TS'
import { products } from "./data.js";
import type { Product } from "./models.js";
import { applyPatch, type Frozen, type Patch } from "./patch.js";
const lamp: Product = products[0]!;
const restocked: Product = applyPatch(lamp, { stock: 55 });
const same: Partial<Product> = {} as Patch<Product>;
// @ts-expect-error stock is a number
applyPatch(lamp, { stock: "fifty" });
// @ts-expect-error Product has no colour property
applyPatch(lamp, { colour: "black" });
const frozen: Frozen<Product> = lamp;
// @ts-expect-error a Frozen property cannot be reassigned
frozen.stock = 0;
export { restocked, same };
TS
npx tsc --noEmitFrozen<T> is the same loop with readonly instead of ?, which is how the built-in Readonly<T> works. The ! after products[0] tells the compiler the element exists, which noUncheckedIndexedAccess otherwise makes you prove.
Check it worked
npx tsc --noEmit prints nothing. All three @ts-expect-error lines are used, so the patch type rejects a wrong value type, an unknown field and a write to a read-only property.
Step 7 · Spot the over-generic mistake
Generics are not free: every type parameter is something a reader has to follow. A useful test is that a type parameter should appear at least twice, linking an input to an output or one input to another. If it appears once, it does nothing a plain type would not do.
Here are two common mistakes and their plain versions:
cd ~/generics-demo
cat > src/plain.ts <<'TS'
import type { Order } from "./models.js";
// Over-generic: T appears once, so it links nothing.
export function labelLoose<T extends { id: string }>(item: T): string {
return `#${item.id}`;
}
// Plain: same behaviour, easier to read.
export function label(item: { id: string }): string {
return `#${item.id}`;
}
// Over-generic: any string is accepted, including codes your app cannot handle.
export function formatMoneyLoose<C extends string>(amount: number, currency: C): string {
return `${currency} ${amount.toFixed(2)}`;
}
// Plain union: the type says exactly which currencies are supported.
export function formatMoney(amount: number, currency: Order["currency"]): string {
return `${currency} ${amount.toFixed(2)}`;
}
TS
cat > src/checks-plain.ts <<'TS'
import { formatMoney, formatMoneyLoose } from "./plain.js";
formatMoneyLoose(10, "EUR");
// @ts-expect-error EUR is not one of the supported currencies
formatMoney(10, "EUR");
TS
npx tsc --noEmitThe generic formatMoneyLoose accepts "EUR" without complaint, even though the app only supports four currencies. The union catches it. Reach for a generic when the caller's type must flow through to the result, as in findById and pluck. Use a union when the set of allowed values is fixed and known.
If your app serves several markets, such as Nigeria, Kenya and Ghana, a union of currency codes keeps a typo such as "NGM" out of a payment screen, and adding a market is one edit to Order["currency"] that the compiler then follows everywhere.
Check it worked
npx tsc --noEmit prints nothing: the loose version accepted "EUR" and the union version rejected it. Look through one file in your own codebase for a type parameter that appears only once and see whether a plain type would do.
Step 8 · Write a typed fetchJson helper and test it
The usual shortcut for loading JSON is return (await response.json()) as T. The as T is a promise to the compiler, not a check: if the server sends something else, your code carries on with the wrong data. This helper takes a type guard, a function that checks the value at run time and tells the compiler what it is. T is inferred from the guard, so callers write no type arguments, and every failure comes back as a Result instead of an exception:
cd ~/generics-demo
cat > src/guards.ts <<'TS'
import type { User } from "./models.js";
export function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "string" &&
"name" in value &&
typeof value.name === "string" &&
"email" in value &&
typeof value.email === "string"
);
}
TS
cat > src/fetch-json.ts <<'TS'
import { fail, ok, type Result } from "./result.js";
export interface FetchProblem {
kind: "timeout" | "network" | "http" | "shape";
message: string;
status?: number;
}
export async function fetchJson<T>(
url: string,
isValid: (value: unknown) => value is T,
timeoutMs = 5000,
): Promise<Result<T, FetchProblem>> {
let response: Response;
try {
response = await fetch(url, {
headers: { accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
const timedOut = error instanceof Error && error.name === "TimeoutError";
return fail<FetchProblem>({
kind: timedOut ? "timeout" : "network",
message: error instanceof Error ? error.message : String(error),
});
}
if (!response.ok) {
return fail<FetchProblem>({ kind: "http", status: response.status, message: response.statusText });
}
let body: unknown;
try {
body = await response.json();
} catch {
return fail<FetchProblem>({ kind: "shape", message: "The body is not valid JSON" });
}
return isValid(body)
? ok(body)
: fail<FetchProblem>({ kind: "shape", message: "The JSON has the wrong shape" });
}
TS
npx tsc --noEmitEvery request gets a timeout through AbortSignal.timeout. On slow or congested mobile networks, which many readers on prepaid data in Africa and elsewhere deal with daily, a request with no timeout can leave a screen spinning forever. Pick a limit that suits your users and show a retry when the result's kind is "timeout".
Now test it with the Node.js test runner. The test starts a small local HTTP server on a free port, so nothing calls the internet. Write one test file for the helper and one for the generic functions:
cd ~/generics-demo
cat > src/fetch-json.test.ts <<'TS'
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, before, test } from "node:test";
import { fetchJson } from "./fetch-json.js";
import { isUser } from "./guards.js";
let server: Server;
let base = "";
before(async () => {
server = createServer((req, res) => {
const send = (status: number, body: string) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(body);
};
if (req.url === "/users/u1") {
send(200, JSON.stringify({ id: "u1", name: "Amara Okafor", email: "amara@example.com" }));
} else if (req.url === "/users/broken") {
send(200, JSON.stringify({ id: 7 }));
} else if (req.url === "/slow") {
setTimeout(() => send(200, "{}"), 1000);
} else {
send(404, JSON.stringify({ error: "not found" }));
}
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => {
server.closeAllConnections();
server.close();
});
test("returns a typed user", async () => {
const result = await fetchJson(`${base}/users/u1`, isUser);
assert.equal(result.ok, true);
if (result.ok) assert.equal(result.value.name, "Amara Okafor");
});
test("reports an HTTP error with its status", async () => {
const result = await fetchJson(`${base}/users/u9`, isUser);
assert.deepEqual(result, { ok: false, error: { kind: "http", status: 404, message: "Not Found" } });
});
test("rejects JSON with the wrong shape", async () => {
const result = await fetchJson(`${base}/users/broken`, isUser);
assert.equal(result.ok ? "ok" : result.error.kind, "shape");
});
test("gives up after the timeout", async () => {
const result = await fetchJson(`${base}/slow`, isUser, 100);
assert.equal(result.ok ? "ok" : result.error.kind, "timeout");
});
TS
cat > src/generics.test.ts <<'TS'
import assert from "node:assert/strict";
import { test } from "node:test";
import { orders, products, users } from "./data.js";
import { findById, first, pluck } from "./generics.js";
import { applyPatch } from "./patch.js";
test("findById finds a record or returns undefined", () => {
assert.equal(findById(users, "u2")?.name, "Kwame Mensah");
assert.equal(findById(orders, "missing"), undefined);
});
test("first returns undefined for an empty list", () => {
assert.equal(first([]), undefined);
});
test("pluck returns one field from each record", () => {
assert.deepEqual(pluck(orders, "total"), [12500, 340]);
});
test("applyPatch changes only the given fields", () => {
const lamp = products[0]!;
assert.deepEqual(applyPatch(lamp, { stock: 55 }), { id: "p1", title: "Solar lamp", stock: 55 });
assert.equal(lamp.stock, 40);
});
TS
npm pkg set scripts.build=tsc "scripts.test=tsc && node --test dist/*.test.js"
npm testnpm test compiles first, so a type error stops the run before any test starts. Node.js 26 can run .ts files directly by removing the types, but it never checks them, so the order "compile, then test" is what makes the type checks count.
Check it worked
The output lists eight passing tests and ends with a summary that includes pass 8 and fail 0. Break the guard on purpose: change typeof value.email === "string" to typeof value.email === "number" in src/guards.ts and run npm test again. The test "returns a typed user" now fails, which is the guard doing its job. Change it back.
When you are finished, remove the demo project:
cd ~
rm -rf ~/generics-demoNext steps
- Go deeper on the
okcheck used withResult: narrow types safely with TypeScript discriminated unions. - Revisit the compiler settings behind every check here: set up a TypeScript 7 project.
- Package what you build: write a Dockerfile for a Node.js app.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
- Write generic functions and types in GoYou will replace three copies of a slice filter with one generic Go 1.27 function, then write constrained helpers, a custom constraint with ~, a generic Set type with an iterator and a generic method, and learn when the standard library or plain code is the better choice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials