Modern mode
Notes
Home | Portfolio
- Loading notes...
- Loading note content...
Modern mode
Home | Portfolio
February 11, 2026
Tags: TypeScript, JavaScript, Tutorial
Generics allow you to write flexible, reusable code while maintaining type safety. Think of them as type parameters for your functions, classes, and interfaces.
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello"); // type is string
const num = identity(42); // type is inferred as number
You can constrain generics to only accept certain types:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): T {
console.log(arg.length);
return arg;
}
logLength("hello"); // OK
logLength([1, 2, 3]); // OK
logLength(42); // Error: number doesn't have length
interface Repository<T> {
find(id: string): Promise<T>;
findAll(): Promise<T[]>;
create(item: T): Promise<T>;
update(id: string, item: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
}
async function fetchData<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error("Failed to fetch");
return res.json() as Promise<T>;
}
interface User {
id: string;
name: string;
email: string;
}
const user = await fetchData<User>("/api/users/1");
Generics are one of TypeScript's most powerful features. Master them and you'll write more flexible, reusable, and type-safe code.