Object-Oriented Programming is a programming paradigm that focuses on organizing code around objects, which are instances of classes. Classes are blueprints for objects that define properties and methods shared by instances. This approach encourages modularity, code reusability, and encapsulation.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
speak(): void {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Buddy");
dog.speak(); // Buddy barks.
Functional Programming treats computation as the evaluation of mathematical functions, avoiding mutable state and side effects. It emphasizes immutability, first-class functions, and the use of higher-order functions.
type NumArray = Array;
const add = (a: number, b: number): number => a + b;
const square = (x: number): number => x * x;
const numbers: NumArray = [1, 2, 3, 4, 5];
const sum = numbers.reduce(add, 0); // 15
const squaredNumbers = numbers.map(square); // [1, 4, 9, 16, 25]
Event-Driven Programming is centered around events, which are changes in state or user actions that trigger specific functions or methods, known as event handlers. This approach is commonly used in GUI applications, web servers, and JavaScript environments.
interface Button {
onClick: (event: MouseEvent) => void;
}
const button: Button = {
onClick: (event) => {
console.log(`Button clicked at (${event.clientX}, ${event.clientY})`);
},
};
// Simulate a click event
const simulatedEvent: MouseEvent = {
clientX: 100,
clientY: 50,
};
button.onClick(simulatedEvent); // Button clicked at (100, 50)