ရိုးရိုးလေး ရှင်းပြမယ်
Class ကို ရိုးရိုးလေး ရှင်းရရင်
Class ဆိုတာ data ပုံစံ တူပြီး အပြုအမူ တူတဲ့ object တွေအတွက် ပုံစံကြမ်း (blueprint) တစ်ခုပါ။ Blueprint က Dog တိုင်းမှာ name ရှိပြီး bark() လုပ်နိုင်တယ်လို့ ပြောပါတယ်။ new Dog("Buddy") က အဲဒီ blueprint ကနေ ခွေးအစစ် တစ်ကောင်ကို ဆောက်ပေးပါတယ်။ Class ကနေ ဆောက်တဲ့ object တိုင်းမှာ ကိုယ်ပိုင် data ရှိပေမယ့် method တွေကိုတော့ မျှသုံးကြပါတယ်။
TypeScript က JavaScript ရဲ့ class syntax ကို ဒီအတိုင်း ထားပြီး type တွေ ထပ်ထည့်ပေးပါတယ်: field တိုင်းမှာ type ကြေညာထားရပြီး constructor parameter တွေမှာလည်း type ရှိပါတယ်။ private လို access modifier တွေက အပြင်က code ဘယ်အပိုင်းကို ထိခွင့်ရှိလဲဆိုတာ compiler ကို ပြောပြပါတယ်။
Problem → Why → Solution
ပြဿနာ: data နဲ့ စည်းမျဉ်းတွေ သီးခြားစီ နေတာ
Class မသုံးဘဲ factory function နဲ့ ရိုးရိုး object literal တွေကို ဆောက်နိုင်ပါတယ်။ ဒါပေမယ့် bank account object က balance ကို ရိုးရိုး property အဖြစ် ဖွင့်ထားရင် ဘယ် code မဆို account.balance = 1000000 လို့ ရေးလို့ ရပါတယ်။ ငွေထုတ်တဲ့ နေရာ သုံးနေရာထဲက တစ်နေရာမှာ balance စစ်ဖို့ မေ့သွားရင်လည်း ဘယ်သူမှ မသိပါဘူး။ Data ကို ကာကွယ်ရမယ့် စည်းမျဉ်းတွေနဲ့ data ကို ချိတ်ပေးထားတာ ဘာမှ မရှိပါဘူး။
function createAccount(owner: string) {
return { owner, balance: 0 };
}
const account = createAccount("Mya");
account.balance += 50; // deposit logic copied into every caller
account.balance = 1_000_000; // nothing stops this
account.balance -= 2_000_000; // overdraft: no rule is checkedဘာ လိုအပ်နေတာလဲ
Data နဲ့ အဲဒါကို စောင့်ရှောက်တဲ့ စည်းမျဉ်းတွေက နေရာ မတူဘဲ ကွဲနေပါတယ်။ Class က နှစ်ခုလုံးကို နေရာတစ်ခုတည်းမှာ စုပေးပါတယ်: field တွေက state ကို သိမ်းပြီး method တွေက state ကို ပြောင်းဖို့ ရည်ရွယ်ထားတဲ့ တစ်ခုတည်းသော လမ်းကြောင်း ဖြစ်ပါတယ်။ Access modifier တွေက အပြင်ကနေ တိုက်ရိုက် ရေးတာကို compiler (#private ဆိုရင် runtime) က တားပေးပါတယ်။
အဓိက concept: blueprint, access နဲ့ inheritance
Class declaration တစ်ခုက enum လိုပဲ အရာနှစ်ခုကို ဆောက်ပါတယ်: new နဲ့ ခေါ်တဲ့ runtime value (constructor function) နဲ့ instance တွေကို ဖော်ပြတဲ့ type ပါ။ TypeScript မှာ field တိုင်းကို class ရဲ့ ထိပ်မှာ type နဲ့ ကြေညာပါတယ်။ Strict mode မှာ field တစ်ခုစီကို ကြေညာချက်မှာ ဒါမှမဟုတ် constructor ထဲမှာ initialise လုပ်ထားလား compiler က စစ်ပေးတာကြောင့် name မပါတဲ့ object ကို မတော်တဆ ဆောက်မိဖို့ မဖြစ်နိုင်ပါဘူး။
Access modifier တွေက member တစ်ခုကို ဘယ်သူ သုံးခွင့်ရှိလဲ ထိန်းပါတယ်။ Default ဖြစ်တဲ့ public က ဘယ်သူမဆို၊ protected က class ကိုယ်တိုင်နဲ့ subclass တွေ၊ private က class ကိုယ်တိုင်ပဲ ဖြစ်ပါတယ်။ ဒီသုံးခုက TypeScript check တွေသာ ဖြစ်ပြီး output ထဲမှာ ပျောက်သွားတာကြောင့် JavaScript သက်သက်၊ JSON.stringify ဒါမှမဟုတ် cast တစ်ခုက value ကို ရောက်နိုင်ပါသေးတယ်။ #balance လို ရေးတဲ့ JavaScript ရဲ့ ကိုယ်ပိုင် #private field တွေကိုတော့ runtime ကိုယ်တိုင် ကာကွယ်ပေးပြီး class body အပြင်ကနေ လုံးဝ မမြင်ရပါဘူး။
| Modifier | ဘယ်သူ သုံးခွင့်ရှိလဲ | ဘယ်သူ ကာကွယ်ပေးလဲ |
|---|---|---|
| public (default) | ဘယ်သူမဆို | — |
| protected | class နဲ့ subclass တွေ | compiler ပဲ |
| private | class ကိုယ်တိုင်ပဲ | compiler ပဲ |
| #name | class ကိုယ်တိုင်ပဲ | JavaScript runtime |
Inheritance က class တစ်ခုကို နောက်တစ်ခုပေါ် ဆောက်ခွင့်ပေးပါတယ်: class Dog extends Animal က Animal ရဲ့ member အားလုံးကို ရပြီး ကိုယ်ပိုင် member တွေ ထပ်ထည့်ပါတယ်။ Base class က object ကို အရင် set up လုပ်ရတာကြောင့် subclass constructor က this ကို မထိခင် super(...) ကို ခေါ်ရပါမယ်။ Subclass က base method ကို အစားထိုးရင် override နဲ့ မှတ်ပါ။ noImplicitOverride option ဖွင့်ထားရင် keyword မေ့တာက error ဖြစ်ပြီး rename လုပ်ပြီးနောက် တိတ်တဆိတ် override မလုပ်တော့တဲ့ method တွေကို ဖမ်းပေးပါတယ်။
နောက်ဆုံးအနေနဲ့ implements Interface က class မှာ interface လိုအပ်တဲ့ member တိုင်း ရှိလား compiler ကို စစ်ခိုင်းတာပါ။ Code ဘာမှ မထပ်ထည့်ပါဘူး၊ ကိုက်မညီတာကို အဝေးက call site မှာ မဟုတ်ဘဲ class ကြေညာတဲ့ နေရာမှာပဲ error အဖြစ် ပြပေးပါတယ်။
One base class, one subclass, one instance
------------------------------------------
class Animal base class
- private name: string
+ move(distance): void
^
| extends (inherits move, adds bark)
|
class Dog subclass
+ bark(): void
|
| new Dog("Buddy")
v
dog { name: "Buddy" } own data on the instance;
bark and move found on the prototypes- Class = constructor value + instance type
- Field တွေကို type ပေး၊ constructor မှာ set
- Modifier က ဘယ်သူ ထိခွင့်ရှိလဲ ဆုံးဖြတ်
- extends + super() နဲ့ base ပေါ် ဆောက်
private က compiler ရဲ့ ကတိ ဖြစ်ပြီး #private က runtime ရဲ့ သော့ ဖြစ်ပါတယ်။
အထွေထွေ ပုံစံ
class Name extends Base implements Contract {
#secret: Type; // runtime-private field
protected shared: Type; // the class and its subclasses
constructor(public readonly id: IdType, value: Type) {
super(/* base constructor arguments */);
this.#secret = value;
this.shared = value;
}
override method(param: Type): Result { /* ... */ }
}Field တွေကို type နဲ့ ကြေညာပြီး constructor ထဲမှာ super() ကို this မသုံးခင် ခေါ်ပါ။ public readonly id လို parameter property က field ကြေညာတာနဲ့ assign လုပ်တာကို တစ်ခါတည်း လုပ်ပေးပါတယ်။
Animal နဲ့ Dog
အောက်က example မှာ private field နဲ့ public method ပါတဲ့ base class တစ်ခု၊ method အသစ်တစ်ခု ထပ်ထည့်တဲ့ subclass တစ်ခု ပါပါတယ်။ Dog မှာ ကိုယ်ပိုင် constructor ဒါမှမဟုတ် name field မရှိတာကို သတိထားကြည့်ပါ၊ ရွှေ့ဖို့ လိုတာ အားလုံးကို Animal ကနေ ရပါတယ်။ console.log တစ်ခါ ခေါ်တိုင်း line တစ်ကြောင်း ထွက်တာကြောင့် output က line နှစ်ကြောင်း ဖြစ်ပါတယ်။
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public move(distance: number): void {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog("Buddy");
dog.bark();
dog.move(10);Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 2
private name: string;Type ပါတဲ့ field ကြေညာချက်ပါ။ private ဖြစ်တာကြောင့် Animal ရဲ့ code ပဲ ဖတ်လို့ရပါတယ်၊ Dog ထဲမှာ this.name နဲ့ အပြင်ကနေ dog.name က compile error ဖြစ်ပါတယ်။
- Lines 4-6
constructor(name: string) {new ခေါ်တဲ့အခါ run ပြီး field ကို assign လုပ်ပါတယ်။ ဒီ assignment ကို ဖြုတ်လိုက်ရင် strict mode က name ကို initialise မလုပ်ထားဘူးလို့ error ပြပါမယ်။
- Line 8
public move(distance: number): void {public method ပါ (public က default ဖြစ်လို့ ရေးတာ မရေးတာ ကိုယ့်သဘောပါ)။ Parameter မှာ type ရှိပြီး void က ဘာမှ ပြန်မပေးဘူးလို့ ပြောပါတယ်။
- Line 13
class Dog extends Animal {Dog က Animal ရဲ့ constructor နဲ့ move ကို အမွေရပြီး bark ကို ထပ်ထည့်ပါတယ်။ Dog မှာ ကိုယ်ပိုင် constructor မရှိတာကြောင့် new Dog("Buddy") က Animal ရဲ့ constructor ကို သုံးပါတယ်။
- Line 21
dog.move(10);Dog instance ပေါ်မှာ အမွေရ method ကို ခေါ်ပါတယ်။ name ကို Animal ရဲ့ constructor က set လုပ်ပြီးသား ဖြစ်လို့ Buddy moved 10m. ကို print ထုတ်ပါတယ်။
Woof! Woof!
Buddy moved 10m.Abstract class, parameter property, override နဲ့ implements
အောက်က example က ဒီ lesson ရဲ့ အပိုင်းအားလုံးကို ပေါင်းထားပါတယ်။ abstract class ကို new နဲ့ တိုက်ရိုက် ဆောက်လို့ မရဘဲ subclass တွေက abstract method တွေကို ဖြည့်ရေးရပါတယ်။ constructor(private radius: number) လို parameter property တွေက field ကြေညာချက်နဲ့ assignment ကို တိုတိုလေး ရေးပေးပါတယ်။ ဒါပေမယ့် enum တွေလိုပဲ code ထုတ်ပေးရတဲ့ syntax ဖြစ်တာကြောင့် type ကိုပဲ ဖယ်တဲ့ tool တွေနဲ့ erasableSyntaxOnly option က အဲဒါကို ငြင်းပါတယ်။
interface Shape {
area(): number;
describe(): string;
}
abstract class BaseShape implements Shape {
constructor(public readonly label: string) {}
abstract area(): number;
describe(): string {
return `${this.label}: ${this.area().toFixed(2)}`;
}
}
class Circle extends BaseShape {
constructor(private radius: number) {
super("circle");
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Square extends BaseShape {
constructor(private side: number) {
super("square");
}
area(): number {
return this.side ** 2;
}
override describe(): string {
return `${super.describe()} (side ${this.side})`;
}
}
const shapes: Shape[] = [new Circle(1), new Square(3)];
shapes.forEach((s) => console.log(s.describe()));
// circle: 3.14
// square: 9.00 (side 3)လက်တွေ့ project တွေမှာ
လက်တွေ့ project: custom error class တွေ
Backend code မှာ class တွေကို service object တွေ (UserService, OrderRepository) အတွက်ရော framework က လိုချင်တဲ့ controller တွေအတွက်ရော တွေ့ရပါတယ်။ ဒါပေမယ့် beginner တွေ အမြန်ဆုံး အကျိုးရှိတဲ့ နေရာကတော့ custom error တွေပါ။ Interface တွေနဲ့ မတူဘဲ class တွေက runtime မှာ ရှိနေတာကြောင့် instanceof နဲ့ စစ်လို့ ရပါတယ်။ ဒါကြောင့် error handler တစ်ခုက HTTP status ကို error ရဲ့ type ကနေ ဆုံးဖြတ်နိုင်ပါတယ်:
class HttpError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = "HttpError";
}
}
class NotFoundError extends HttpError {
constructor(resource: string) {
super(404, `${resource} not found`);
this.name = "NotFoundError";
}
}
function toResponse(err: unknown): string {
if (err instanceof HttpError) return `${err.status} ${err.message}`;
return "500 Internal Server Error";
}
console.log(toResponse(new NotFoundError("Order 42"))); // 404 Order 42 not found
console.log(toResponse(new Error("boom"))); // 500 Internal Server ErrorRoute handler တွေက throw new NotFoundError("Order 42") လို့ပဲ ရေးပြီး status code ကို နေရာတစ်ခုတည်းမှာ ဆုံးဖြတ်ပါတယ်။ Error အမျိုးအစား အသစ် လိုလာရင် subclass တစ်ခု ထပ်ထည့်ရုံပါပဲ။ instanceof HttpError က NotFoundError ကိုပါ ဖမ်းတာကြောင့် handler ကို ပြင်စရာ မလိုပါဘူး။ this.name ကို set လုပ်ထားတာကြောင့် log ထဲမှာလည်း ရိုးရိုး "Error" အစား "NotFoundError" ကို မြင်ရပြီး production မှာ ပြဿနာ ရှာရတာ ပိုမြန်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားများ
1. private က runtime မှာ data ကို ဝှက်ပေးမယ်လို့ ထင်တာ
private secret = 1 ပါတဲ့ object ကို JSON.stringify လုပ်ရင် {"secret":1} ထွက်ပြီး console.log ကလည်း ပြပါတယ်။ (obj as any).secret = 5 လည်း အလုပ်လုပ်ပါတယ်။ Token ဒါမှမဟုတ် password လို တကယ် ဝှက်ရမယ့် data အတွက် runtime က ကာကွယ်ပေးတဲ့ #secret ကို သုံးပါ။
2. Method ကို callback အဖြစ် ပေးတဲ့အခါ this ပျောက်တာ
["pen"].forEach(cart.add) လို့ ရေးရင် add ထဲမှာ this က undefined ဖြစ်ပြီး "Cannot read properties of undefined" ဆိုတဲ့ TypeError နဲ့ crash ဖြစ်ပါတယ်၊ compiler ကတော့ ဘာမှ မပြောပါဘူး။ (item) => cart.add(item) လို arrow function နဲ့ wrap လုပ်ပါ၊ ဒါမှမဟုတ် method ကို add = (item: string) => { ... } လို arrow-function property အဖြစ် ရေးပါ။
3. super() မခေါ်ခင် this သုံးတာ ဒါမှမဟုတ် ! နဲ့ field ကို ဖုံးတာ
Subclass constructor ထဲမှာ super() မတိုင်ခင် this.x = 1 လို့ ရေးရင် error TS17009 ရပါတယ်၊ super() ကို ပထမဆုံး ခေါ်ပါ။ "has no initializer" error ကို name!: string လို definite assignment ! နဲ့ ပိတ်တာကလည်း undefined field ကို ဖုံးထားရုံပါ၊ constructor ထဲမှာ တကယ် assign လုပ်ပါ။
Best Practices
အကောင်းဆုံး လုပ်ထုံးများ
- Class က state နဲ့ စည်းမျဉ်းတွေကို တကယ် ပေါင်းစုရမှ သုံးပါ၊ data သက်သက်အတွက် interface နဲ့ object literal က လုံလောက်ပါတယ်။
- တကယ် ဝှက်ရမယ့် data အတွက် #private ကို သုံးပြီး ကျန်တာတွေအတွက် private ကို သုံးပါ။
- tsconfig မှာ noImplicitOverride ကို ဖွင့်ပြီး အစားထိုး method တိုင်းကို override နဲ့ မှတ်ပါ။
- Inheritance အဆင့် တစ်ဆင့်၊ နှစ်ဆင့်ထက် မနက်ပါစေနဲ့၊ ပိုရှုပ်လာရင် composition ကို စဉ်းစားပါ။
Mini challenge
Bank account နဲ့ savings account
Balance ကို runtime-private field ထဲ ကာကွယ်ထားပြီး စည်းမျဉ်းတွေကို method တွေထဲမှာပဲ ထားတဲ့ account class တစ်ခု ရေးပါ။ ပြီးရင် interest ထည့်ပေးတဲ့ subclass တစ်ခုနဲ့ ချဲ့ပါ။
- BankAccount မှာ readonly owner နဲ့ #balance (0 ကနေ စ) ပါရပါမယ်။
- deposit က 0 နဲ့ အောက် amount ကို Error throw လုပ်ပြီး withdraw က balance ထက် များရင် "Insufficient funds" ကို throw လုပ်ရပါမယ်။
- getBalance() နဲ့ describe() ("Mya: 408" ပုံစံ) method တွေ ပါရပါမယ်။
- SavingsAccount extends BankAccount မှာ rate ပါပြီး addInterest() နဲ့ override describe() ပါရပါမယ်။
class BankAccount {
// TODO: a runtime-private #balance field starting at 0
constructor(readonly owner: string) {}
deposit(amount: number): void {
// TODO: throw for amount <= 0, otherwise add to the balance
}
withdraw(amount: number): void {
// TODO: throw "Insufficient funds" when amount > balance
}
// TODO: getBalance(): number and describe(): string
}
// TODO: class SavingsAccount extends BankAccount
// - constructor(owner, rate) calls super(owner)
// - addInterest() deposits Math.round(balance * rate)
// - override describe() appends " (savings, 2%)"
// TODO: deposit 500, withdraw 100, add interest, print describe(),
// then try to withdraw 10000 and print the error messageရလဒ်: "Mya: 408 (savings, 2%)" နဲ့ "Insufficient funds" ဆိုတဲ့ line နှစ်ကြောင်း ထွက်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Subclass က #balance ကို တိုက်ရိုက် မမြင်ရပါဘူး၊ getBalance() နဲ့ deposit() ကို သုံးပါ။ describe() ကို override လုပ်တဲ့အခါ super.describe() နဲ့ base version ကို ပြန်သုံးလို့ ရပါတယ်။
အဖြေ ကြည့်ရန်
class BankAccount {
#balance = 0;
constructor(readonly owner: string) {}
deposit(amount: number): void {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#balance += amount;
}
withdraw(amount: number): void {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#balance -= amount;
}
getBalance(): number {
return this.#balance;
}
describe(): string {
return `${this.owner}: ${this.#balance}`;
}
}
class SavingsAccount extends BankAccount {
constructor(owner: string, private rate: number) {
super(owner);
}
addInterest(): void {
this.deposit(Math.round(this.getBalance() * this.rate));
}
override describe(): string {
return `${super.describe()} (savings, ${this.rate * 100}%)`;
}
}
const savings = new SavingsAccount("Mya", 0.02);
savings.deposit(500);
savings.withdraw(100);
savings.addInterest();
console.log(savings.describe());
try {
savings.withdraw(10_000);
} catch (err) {
console.log(err instanceof Error ? err.message : err);
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Class က constructor value နဲ့ instance type ကို ဆောက်ပေးပြီး strict mode က field တိုင်း initialise ဖြစ်ကြောင်း စစ်ပါတယ်။
- public, protected, private က compile time မှာပဲ စစ်ပြီး #private ကို runtime က ကာကွယ်ပါတယ်။
- extends က base class ကို ပြန်သုံးစေပြီး super() ကို this မတိုင်ခင် ခေါ်ရကာ အစားထိုး method တွေကို override နဲ့ မှတ်ပါ။
- implements က class ကို interface နဲ့ တိုက်စစ်ပြီး class တွေက runtime မှာ ရှိတာကြောင့် instanceof နဲ့ စစ်လို့ ရပါတယ်။
TypeScript Handbook — TypeScript