📘
Generics: Writing Reusable Code
Beginner
100 XP
40 min
Lesson Content
Generics in TypeScript
Generics allow you to write reusable code that works with multiple types. Essential for React hooks and Vue composables.
Generic Functions
function identity(arg: T): T {
return arg;
}
let output = identity("hello");
let number = identity(42); Generic Interfaces
interface Box {
value: T;
}
let stringBox: Box = { value: "hello" };
let numberBox: Box = { value: 42 }; Generic Classes
class Stack {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
} Multiple Type Parameters
function pair(first: T, second: U): [T, U] {
return [first, second];
} Example Code
Create generic functions and classes
function getFirst<T>(items: T[]): T | undefined {
return items[0];
}
const numbers = [1, 2, 3];
const names = ["Alice", "Bob"];
console.log(getFirst(numbers));
console.log(getFirst(names));Expected Output:
1 Alice
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code