Classes and Objects in TypeScript
Awesome! Let's now cover Classes and Objects in TypeScript, which are at the core of building services, components, and models in Angular.
🔹 1. What is a Class?
A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods).
✅ Basic Syntax
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name}`);
}
}
🔹 2. Creating an Object
You can create objects (instances) from a class using the new keyword.
const person1 = new Person("Alice", 30);
person1.greet(); // Output: Hello, my name is Alice
🔹 3. Access Modifiers
| Modifier | Description |
|---|---|
public |
Accessible anywhere (default) |
private |
Accessible only within the class |
protected |
Accessible in the class & subclasses |
class Employee {
private salary: number;
constructor(private name: string, salary: number) {
this.salary = salary;
}
getSalary(): number {
return this.salary;
}
}
🔹 4. Inheritance
Classes can extend other classes using extends.
class Manager extends Employee {
department: string;
constructor(name: string, salary: number, department: string) {
super(name, salary);
this.department = department;
}
display(): void {
console.log(`${this.name} manages ${this.department}`);
}
}
🔹 5. Getter & Setter
Encapsulation using get and set methods:
class Product {
private _price: number;
constructor(price: number) {
this._price = price;
}
get price(): number {
return this._price;
}
set price(value: number) {
if (value > 0) {
this._price = value;
}
}
}
🔹 6. Interfaces with Classes
A class can implement one or more interfaces.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log("Log:", message);
}
}
🧠Summary
- Use classes to encapsulate logic and data.
- Create objects using
new. - Apply access modifiers to control visibility.
- Extend classes using inheritance.
- Use getters and setters for controlled access.
- Implement interfaces for structured behavior.
Comments
Post a Comment