TypeScript Classes
Building blocks for object-oriented programming
🏗️ What are TypeScript Classes?
Classes are blueprints for creating objects with properties and methods. They help organize code by grouping related data and functions together, making your programs more structured and reusable.
// Simple class example
class Person {
name: string;
age: number;
}
const john = new Person();
john.name = "John";
john.age = 25;
Output:
Person { name: "John", age: 25 }
Key Class Concepts
Properties
Variables that belong to a class
class Car {
brand: string;
model: string;
}
Methods
Functions that belong to a class
class Dog {
bark() {
return "Woof!";
}
}
Objects
Instances created from classes
const myCar = new Car();
myCar.brand = "Toyota";
Access Modifiers
Control property visibility
class User {
public name: string;
private password: string;
}
🔹 Creating a Basic Class
Here's how to define and use a simple class:
class Student {
name: string;
grade: number;
study() {
return `${this.name} is studying`;
}
}
// Create an object
const student1 = new Student();
student1.name = "Alice";
student1.grade = 10;
console.log(student1.study());
Output:
Alice is studying
🔹 Class with Properties and Methods
Combine data and behavior in one class:
class Calculator {
result: number = 0;
add(num: number) {
this.result += num;
return this;
}
subtract(num: number) {
this.result -= num;
return this;
}
getResult() {
return this.result;
}
}
const calc = new Calculator();
calc.add(10).subtract(3);
console.log(calc.getResult());
Output:
7
🔹 Access Modifiers
Control who can access class members:
class BankAccount {
public accountHolder: string;
private balance: number = 0;
protected accountNumber: string;
public deposit(amount: number) {
this.balance += amount;
}
public getBalance() {
return this.balance;
}
}
const account = new BankAccount();
account.accountHolder = "John Doe";
account.deposit(1000);
console.log(account.getBalance());
// account.balance = 5000; // Error: private property
Output:
1000
- public: Accessible everywhere (default)
- private: Only accessible within the class
- protected: Accessible in class and subclasses
🔹 Readonly Properties
Create properties that cannot be changed after initialization:
class Book {
readonly isbn: string;
title: string;
constructor(isbn: string, title: string) {
this.isbn = isbn;
this.title = title;
}
}
const book = new Book("978-0-123456-78-9", "TypeScript Guide");
console.log(book.isbn);
// book.isbn = "new-isbn"; // Error: readonly property
Output:
978-0-123456-78-9