The core idea
Use a generic when your function, type, or component must work with many types and keep the exact type linked across the code.
If the type does not need to travel from input to output, you probably do not need a generic.
Why it matters
In hackathon apps, you often repeat the same pattern: load users, load events, filter tasks, pick one item, store API responses. Generics let you write one helper and still keep strong types.
This helps your repo look cleaner to reviewers. It also avoids switching back to any just because one helper is shared across different data.
Simple reusable helper
Here is a helper that returns the first item from any list. The generic T means TypeScript remembers what the list contains.
function first<T>(items: T[]): T | undefined {
return items[0];
}
type Student = {
id: string;
name: string;
college: string;
};
const names = ["Asha", "Ravi", "Meera"];
const firstName = first(names);
// firstName is string | undefined
const students: Student[] = [
{ id: "s1", name: "Asha", college: "VIT" }
];
const firstStudent = first(students);
// firstStudent is Student | undefinedHow to use one
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Typed API shape
A common use is wrapping API results. The outer shape is the same, but the data changes for each call.
type ApiResult<T> = {
ok: boolean;
data: T;
error?: string;
};
type Event = {
id: string;
title: string;
feeRupees: number;
};
const eventResult: ApiResult<Event[]> = {
ok: true,
data: [
{ id: "e1", title: "College Hack Night", feeRupees: 0 }
]
};
const title = eventResult.data[0]?.title;
// TypeScript knows title is string | undefinedDo not overdo it
Beginners often add generics to look advanced. This makes code harder to read and does not catch more bugs.
If a function only accepts strings, write string. If a type is used once and has no changing inner data, keep it simple.
// Too much
function shout<T extends string>(text: T): string {
return text.toUpperCase();
}
// Clearer
function shout(text: string): string {
return text.toUpperCase();
}Ask AI carefully
You can ask an AI tool to suggest where generics help in your project. Do not accept a rewrite blindly.
Check that each generic connects at least two places, like input to output or wrapper to data. If it appears only once, it is usually not useful.
Prompt:
I am converting this JavaScript file to TypeScript.
Suggest only the places where a generic would make the types safer.
Do not add generics for simple string or number functions.
Explain why each generic is needed.Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done