Typed functions & generics
Parameter and return types, optional parameters, function types and reusable generic code.
Type function parameters and, for public functions, the return type. Optional parameters use ?; default values work as in JavaScript.
Generics let one function or type work with many types while keeping them connected. <T> is a type parameter — a placeholder filled in when the function is used. Instead of returning any, a generic function returns exactly the type you passed in.
You already use generics: Array<string>, Promise<User> and React's useState<number>.
Example code
Try it in the TypeScript Playground or with tscfunction first<T>(items: T[]): T | undefined {
return items[0];
}
const city = first(["Kochi", "Trivandrum"]); // type: string | undefined
const score = first([92, 85]); // type: number | undefined
interface ApiResponse<T> {
data: T;
page: number;
}
type JobSummary = { id: number; title: string };
const res: ApiResponse<JobSummary[]> = {
data: [{ id: 1, title: "React Developer" }],
page: 1
};
console.log(city, score, res.data[0].title);
Compiler / program output
Kochi 92 React Developer
Paste the code into the official TypeScript Playground in your browser, or install TypeScript (npm install -D typescript) and run npx tsc --noEmit to type-check. Names are fictional.
Key points
- Type parameters and return values of functions.
- Generics (<T>) make reusable code that keeps exact types.
- Array<T>, Promise<T> and useState<T> are generics.
- A generic interface such as ApiResponse<T> types API wrappers.
Quick check
What is the main benefit of a generic function over one that uses any?
With generics the returned type matches the input type, so later code stays type-checked; any would throw that information away.
Practice task
Write a generic function groupBy<T>(items: T[], key: keyof T) that returns an object grouping items by that key, and test it with a list of jobs grouped by city.
Interview corner
What are generics?
Type parameters that let you write reusable functions, classes and types that work with many types while preserving the relationship between input and output types — for example Array<T> or Promise<T>.
What does keyof do?
keyof T produces a union of T's property names as string literals, so a parameter typed as keyof T only accepts real property names.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.