TypeScriptIntermediate
TypeScript Classes (ক্লাস)
Class type, implements, access modifier, parameter property, abstract class ও static member — বাংলায় সম্পূর্ণ গাইড।
16টি অংশবাংলা ভাষায়
Class হলো object তৈরি করার ছাঁচ। TypeScript-এ class-এ টাইপ, access control ও interface বাস্তবায়ন (implements) যোগ হয় — অর্গানাইজড OOP কোড সহজে লেখা যায়।
Class Type ও implements
interface Pointable {
x: number;
y: number;
}
class Point implements Pointable {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(3, 4);Access Modifiers
class BankAccount {
public owner: string; // সবাই দেখতে পারে
private balance: number; // class-এর ভেতরেই
protected id: string; // subclass-এ দৃশ্য
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
this.id = "acc-" + Math.random();
}
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const acc = new BankAccount("রহিম", 100);
// acc.balance = 0; // ❌ private
console.log(acc.getBalance()); // 100readonly Properties
class User {
readonly createdAt: Date;
constructor(public name: string) {
this.createdAt = new Date();
}
}
const u = new User("করিম");
// u.createdAt = new Date(); // ❌ readonlyParameter Properties
Constructor প্যারামিটারে public/private ইত্যাদি দিলে নিজে থেকেই property ঘোষণা ও assign হয় — কোড ছোট হয়ে যায়।
class Product {
constructor(
public name: string,
private price: number,
public readonly sku: string,
) {}
showPrice(): string {
return this.name + ": " + this.price + "৳";
}
}
const phone = new Product("বাংলাফোন", 15000, "B-100");
console.log(phone.showPrice());Abstract Class
Abstract class সরাসরি object বানাতে দেয় না — শুধু subclass-এর ছাঁচ নির্ধারণ করে। বাধ্যতামূলক abstract method-গুলো subclass-কে লিখতে হয়।
abstract class Shape {
abstract area(): number;
describe(): string {
return "একটি আকৃতি";
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
const circle: Shape = new Circle(5);static Members
class Config {
static appName = "TechTutor";
static version = "1.0.0";
static info(): string {
return Config.appName + " v" + Config.version;
}
}
console.log(Config.info()); // TechTutor v1.0.0class বনাম interface
interface শুধু গঠন বর্ণনা করে (runtime-এ থাকে না), class বাস্তব implementation ও value দেয়। ডেটা শেপ চাইলে interface, লজিক চাইলে class।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।