Lesson 4 • Intermediate
Functions and Generics 🔧
Type your function parameters, return values, and overloads — then write flexible, reusable code with generics that work with any type.
What You'll Learn in This Lesson
- • Type function parameters, return values, and rest parameters
- • Optional parameters, defaults, and function overloads
- • Generics:
<T>syntax, constraints, andkeyof - • Generic interfaces, classes, and the Result pattern
- • Real-world patterns:
ApiResponse<T>,Stack<T>
1️⃣ Typed Functions
TypeScript lets you annotate function parameters and return types, giving you compile-time safety for every function call. Optional parameters use ? and function overloads let you define multiple call signatures.
Try It: Typed Functions
Parameters, returns, optionals, rest params, and overloads
// Typed Functions in TypeScript
console.log("=== Function Parameter & Return Types ===");
console.log();
// Basic typed function
console.log("function add(a: number, b: number): number {");
console.log(" return a + b;");
console.log("}");
function add(a, b) { return a + b; }
console.log("add(5, 3) = " + add(5, 3));
console.log();
// Optional parameters
console.log("=== Optional Parameters ===");
function greet(name, greeting) {
greeting = greeting || "Hello";
return greeting + ", " + na
...2️⃣ Generics
Generics let you write functions, interfaces, and classes that work with any type while preserving type safety. The <T> is a type variable that gets filled in when you call the function.
Try It: Generics
Generic functions, constraints, keyof, and multiple type params
// Generics — Write Once, Use with Any Type
console.log("=== Why Generics? ===");
console.log();
// Without generics — you lose type info
console.log("// WITHOUT generics:");
console.log("function firstItem(arr: any[]): any { return arr[0]; }");
console.log("// Returns 'any' — you lose all type information!");
console.log();
// With generics — type preserved
console.log("// WITH generics:");
console.log("function firstItem<T>(arr: T[]): T { return arr[0]; }");
console.log("firstItem([1,2,3])
...3️⃣ Generic Patterns
Generics shine in real-world patterns like API response wrappers, data structures, and the Result type for error handling.
Try It: Generic Patterns
ApiResponse<T>, Stack<T>, and Result<T, E>
// Generic Interfaces, Classes, and Real-World Patterns
console.log("=== Generic Interfaces ===");
console.log();
console.log("interface ApiResponse<T> {");
console.log(" data: T;");
console.log(" status: number;");
console.log(" message: string;");
console.log("}");
console.log();
let userResponse = { data: { id: 1, name: "Alice" }, status: 200, message: "OK" };
let postsResponse = { data: [{ id: 1, title: "Hello" }], status: 200, message: "OK" };
console.log("ApiResponse<User>: " + JSON.
...⚠️ Common Mistakes
.length, constrain to { length: number } not string.T is only used once, you don't need a generic. Use the concrete type instead.TData, TError, TKey instead of just T, U, V.📋 Quick Reference
| Pattern | Syntax |
|---|---|
| Typed function | (a: number): string |
| Optional param | (name?: string) |
| Generic func | function f<T>(x: T): T |
| Constraint | <T extends HasLength> |
| keyof | <K extends keyof T> |
| Generic interface | interface Box<T> { val: T } |
🎉 Lesson Complete!
You've mastered typed functions and generics! Next, explore classes and OOP in TypeScript.
Sign up for free to track which lessons you've completed and get learning reminders.