TypeScript OOP Enums Classes and Dynamic Methods

TypeScript Series Part 3: OOP – Enums, Classes, and Dynamic Methods! 🚀 As I dive deeper into my TypeScript journey, Part 3 has been all about building structured, scalable code using Object-Oriented Programming (OOP) principles. Here’s a breakdown of what I covered today: 1. Enums (Enumerations) Enums allow us to define a set of named constants. Instead of using magic strings or numbers, Enums make the code readable and type-safe. Example: Defining user roles or application states. typescript enum UserRole { Admin = "ADMIN", Trainer = "TRAINER", Student = "STUDENT" } Use code with caution. 2. Classes & Constructors Classes are blueprints for objects. The Constructor is a special method that runs automatically when a new object is created, helping us initialize properties instantly. Example: typescript class Laptop { brand: string; constructor(brandName: string) { this.brand = brandName; } } const myLaptop = new Laptop("Dell"); Use code with caution. 3. Dynamic Methods Methods are functions defined inside a class. They become "dynamic" when they can take arguments to perform different actions based on the input, allowing the object to "do" something. Example: typescript class Calculator { multiply(a: number, b: number): number { return a * b; } } Use code with caution. Putting it all together: typescript enum ProjectStatus { Pending = "PENDING", Ongoing = "ONGOING", Done = "DONE" } class Project { constructor(public title: string, public status: ProjectStatus) {} updateStatus(newStatus: ProjectStatus) { this.status = newStatus; console.log(`Project "${this.title}" is now ${this.status}`); } } const myTask = new Project("TypeScript Part-3", ProjectStatus.Ongoing); myTask.updateStatus(ProjectStatus.Done); Use code with caution. Special thanks to my trainer Ram Shankar Darivemula and the team at Frontlines EduTech (FLM) for making these complex concepts so easy to grasp! Onto the next challenge! 💻🔥 #TypeScript #Coding #WebDevelopment #SoftwareEngineering #LearningJourney #OOP #TechCommunity

To view or add a comment, sign in

Explore content categories