Lesson 6 of 7
Introduction to Generics
Generics let you write functions and types that work across many types while preserving type information. Instead of accepting and returning `any`, a generic function says 'I take a value of type T and return a value of the same type T - the caller decides what T is'. Generics are the foundation of reusable, type-safe utilities.
Generics - Functions, Interfaces & Constraints
// ── Problem without generics ─────────────────────────────────
function identity(value: any): any {
return value;
}
const result = identity("hello"); // Type: any - type information lost!
// ── With generics - type flows through ───────────────────────
function identity<T>(value: T): T {
return value;
}
const s = identity("hello"); // Type: string ✅
const n = identity(42); // Type: number ✅
const b = identity(true); // Type: boolean ✅
// ── Explicit type argument (usually inferred) ─────────────────
const explicit = identity<string>("hello"); // ✅ same result
// ── Generic functions - preserving input/output relationship ──
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const firstTask = first(tasks); // Type: Task | undefined
function wrap<T>(value: T): { value: T } {
return { value };
}
const wrapped = wrap(42); // Type: { value: number }
// ── Multiple type parameters ──────────────────────────────────
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const p = pair("Alice", 30); // Type: [string, number]
// ── Generic interfaces ────────────────────────────────────────
interface ApiResponse<T> {
data: T;
status: number;
message: string;
timestamp: Date;
}
interface Paginated<T> {
items: T[];
total: number;
page: number;
perPage: number;
lastPage: number;
}
// Composable:
type PaginatedTasksResponse = ApiResponse<Paginated<Task>>;
// ── Generic constraints - extends ─────────────────────────────
// Constraint: T must have an 'id' property
function findById<T extends { id: number }>(
items: T[],
id: number,
): T | undefined {
return items.find((item) => item.id === id);
}
findById(tasks, 1); // ✅ Task has id: number
findById(users, 1); // ✅ User has id: number
// findById(["strings"], 1); // ❌ string has no 'id'
// ── keyof constraint - accessing known properties ─────────────
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const title = getProperty(task, "title"); // Type: string
const priority = getProperty(task, "priority"); // Type: Priority
// getProperty(task, "nonexistent"); // ❌ ErrorCommon Mistakes
- Using `any` when a generic would work - `function wrap(v: any): { value: any }` loses all type info. Use `function wrap<T>(v: T): { value: T }` to preserve it.
- Forgetting constraints - if your generic function accesses a property, you MUST constrain T. Unconstrained T can be any type, including types that don't have the property.
- Over-constraining generics - `T extends object` is too loose for some cases and too tight for others. Match the constraint exactly to what your function needs. Use `T extends { id: number }` rather than `T extends object`.
Tip
Tip
Practice Introduction to Generics in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Introduction to Generics
Practice Task
Note
Practice Task - (1) Write a working example of Introduction to Generics from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Introduction to Generics is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Generics let you write functions and types that work across many types while preserving type information.
- Using `any` when a generic would work - `function wrap(v: any): { value: any }` loses all type info. Use `function wrap<T>(v: T): { value: T }` to preserve it.
- Forgetting constraints - if your generic function accesses a property, you MUST constrain T. Unconstrained T can be any type, including types that don't have the property.
- Over-constraining generics - `T extends object` is too loose for some cases and too tight for others. Match the constraint exactly to what your function needs. Use `T extends { id: number }` rather than `T extends object`.
Finished this lesson?