ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Part 2 ရဲ့ TaskManager ထဲမှာ အလုပ်နှစ်မျိုး ရောနေပါတယ်။ တစ်ခုက task rule တွေ (id တိုးတာ၊ status ပြောင်းတာ) ဖြစ်ပြီး နောက်တစ်ခုက ပစ္စည်းတွေကို array ထဲ သိမ်းတာ၊ ရှာတာပါ။ ဒုတိယအလုပ်က task နဲ့ မဆိုင်ပါဘူး။ Tag တွေ၊ user တွေ၊ project တွေ သိမ်းဖို့လည်း အတူတူပဲ လိုပါတယ်။
ဗီရိုတစ်လုံးကို စဉ်းစားကြည့်ပါ။ ဗီရိုက ထဲမှာ ဘာထည့်ထားလဲ မသိဘဲ "ထည့်"၊ "အကုန်ပြ"၊ "ရှာ" ဆိုတဲ့ အလုပ်တွေကို လုပ်ပေးနိုင်ပါတယ်။ Generic Repository<T> က ဒီလို ဗီရိုပါ။ new Repository<Task>() လို့ ရေးလိုက်တဲ့အချိန်ကျမှ "ဒီဗီရိုထဲမှာ Task တွေပဲ ထည့်မယ်" လို့ label ကပ်ပေးပါတယ်။
Problem → Why → Solution
ပြဿနာ: type တစ်ခုပြောင်းတိုင်း class တစ်ခု copy
Task တွေကို tag တွေနဲ့ အုပ်စုဖွဲ့ချင်လာတယ်ဆိုပါစို့။ အမြန်ဆုံးနည်းက storage class ကို copy ကူးပြီး Task နေရာမှာ string လို့ ပြောင်းလိုက်တာပါ။ Code က အလုပ်လုပ်ပါတယ်၊ ဒါပေမယ့် တစ်နေ့ find() မှာ bug တစ်ခု ပြင်ရရင် နေရာနှစ်ခုမှာ ပြင်ရပါမယ်၊ User store ထပ်လိုရင် သုံးခုဖြစ်လာပါမယ်။
နောက်ထပ် "ဖြေရှင်းနည်း" တစ်ခုက items: any[] လို့ ရေးပြီး class တစ်ခုတည်း ထားတာပါ။ ဒါပေမယ့် ဒါဆိုရင် Task store ထဲကို number တွေ ထည့်လို့ရသွားပြီး find() က ပြန်ပေးတဲ့ value ရဲ့ .title ကို စစ်ပေးမယ့်သူ မရှိတော့ပါဘူး။
class TaskStore {
private items: Task[] = [];
add(item: Task): void { this.items.push(item); }
find(match: (t: Task) => boolean): Task | undefined {
return this.items.find(match);
}
}
// The same code again; only the type changed.
class TagStore {
private items: string[] = [];
add(item: string): void { this.items.push(item); }
find(match: (t: string) => boolean): string | undefined {
return this.items.find(match);
}
}ဘာကြောင့် generic လိုတာလဲ
Class နှစ်ခုရဲ့ logic က တစ်ထပ်တည်းဖြစ်ပြီး ကွာတာက type ပဲ ဖြစ်ပါတယ်။ Function တစ်ခုက value ကို parameter အဖြစ် လက်ခံသလို generic က type ကို parameter (T) အဖြစ် လက်ခံပါတယ်။ ဒါကြောင့် logic ကို တစ်ခါပဲ ရေးပြီး type safety လည်း မဆုံးရှုံးပါဘူး။
Core concept: generic storage + task rules
class Repository<T> မှာ T က နေရာယူထားတဲ့ type ပါ။ new Repository<Task>() လို့ ရေးလိုက်ရင် class ထဲက T တိုင်းက Task ဖြစ်သွားပါတယ်။ add() က Task ကိုပဲ လက်ခံပြီး find() က Task | undefined ကို ပြန်ပေးပါတယ်။ new Repository<string>() ဆိုရင်တော့ အဲဒီ code တစ်ခုတည်းက string တွေအတွက် အလုပ်လုပ်ပါတယ်။ Runtime မှာ class တစ်ခုပဲ ရှိပြီး T ဆိုတာ မရှိတော့ပါဘူး၊ စစ်ဆေးမှုအားလုံးက compile time မှာ ဖြစ်ပါတယ်။
Type argument ကို မပေးဘဲ new Repository() လို့ ရေးရင် ဘာဖြစ်မလဲ။ Constructor မှာ T ကို ခန့်မှန်းစရာ argument မရှိလို့ TypeScript က T ကို unknown လို့ ယူပါတယ် (any မဟုတ်ပါ)။ add() က ဘာမဆို လက်ခံသွားပြီး getAll() ကနေ ရလာတဲ့ value ရဲ့ .title ကို ဖတ်ရင် "Object is of type 'unknown'" error ရပါတယ်။ ဒါကြောင့် field initializer လို ခန့်မှန်းစရာ မရှိတဲ့နေရာမှာ <Task> ကို အမြဲ ရေးပါ။
TaskManager က Repository<Task> ကို extends မလုပ်ဘဲ private field တစ်ခုအဖြစ် ကိုင်ထားပါတယ်။ ဒါကို composition ("has-a") လို့ ခေါ်ပါတယ်။ extends လုပ်ခဲ့ရင် add() က public method ဖြစ်သွားပြီး caller တွေက id မတိုးဘဲ၊ status မစစ်ဘဲ task တွေကို တိုက်ရိုက် ထည့်နိုင်သွားပါမယ်။ Composition နဲ့ဆိုရင် Repository က သိမ်းတာပဲ လုပ်ပြီး task rule တွေကို TaskManager တစ်ခုတည်းက ပိုင်ပါတယ်။
အပြီးသတ်ချက် နှစ်ခုလည်း ပါပါတယ်။ getAll() က readonly T[] ကို ပြန်ပေးလို့ caller က ဖတ်လို့ရပေမယ့် push() လုပ်ရင် compile error ပါ။ getStats() က [total: number, done: number] ဆိုတဲ့ labeled tuple ကို ပြန်ပေးပါတယ်။ Tuple က length နဲ့ အစီအစဉ် ပုံသေဖြစ်ပြီး label တွေက editor မှာ ဘယ်နေရာက ဘာလဲ ပြပေးပါတယ်။ နောက်ဆုံးအနေနဲ့ updateStatus() က false ပြန်မပေးတော့ဘဲ TaskNotFoundError ကို throw လုပ်ပါတယ်။ Caller က မေ့ပြီး မစစ်မိရင်တောင် error က တိတ်တဆိတ် ပျောက်မသွားပါဘူး။
| false ပြန်ပေးတာ (Part 2) | Error throw တာ (Part 3) | |
|---|---|---|
| Caller မစစ်ရင် | Failure တိတ်တဆိတ် ပျောက် | Program က ချက်ချင်း သိ |
| အကြောင်းရင်း ပြနိုင်လား | true/false ပဲ | message နဲ့ error type |
| သင့်တော်တဲ့နေရာ | ပုံမှန် ဖြစ်တတ်တဲ့ miss | မဖြစ်သင့်တဲ့ အခြေအနေ |
- Repository<T> က သိမ်း/ရှာ ပဲ လုပ်
- <Task> က ဗီရိုကို label ကပ်
- TaskManager က ဗီရိုကို ပိုင်ပြီး rule စောင့်
- Stats ကို tuple၊ miss ကို error
Generic class က "ဘယ်လို သိမ်းမလဲ" ကို ဖြေပြီး TaskManager က "task ဆိုတာ ဘယ်လို ပြုမူရမလဲ" ကို ဖြေပါတယ်။
အခြေခံ ပုံစံ
class Store<T> {
private items: T[] = [];
add(item: T): void { /* push */ }
all(): readonly T[] { return this.items; }
}
class Service {
private store = new Store<Entity>(); // composition, explicit <T>
stats(): [count: number, active: number] { /* ... */ }
}Generic class တစ်ခုက storage ကို ကိုင်ပြီး service class က အဲဒါကို private field အဖြစ် ထားကာ ကိုယ်ပိုင် rule နဲ့ tuple လို result type တွေကို ထုတ်ပေးပါတယ်။
Part 3 code: project အပြည့်အစုံ
TaskStatus နဲ့ Task က Part 1 ကတည်းက မပြောင်းပါဘူး။ Part 2 ရဲ့ private tasks array နေရာမှာ private repo = new Repository<Task>() ဝင်လာပြီး updateStatus() က error throw လုပ်ပါတယ်။ Demo အဆုံးမှာ Repository ကို string တွေအတွက်ပါ ပြန်သုံးပြထားပါတယ်။ Error line ကို console.log နဲ့ ထုတ်ထားတာက output တစ်ခုတည်းထဲမှာ မြင်ရအောင်ပါ။ CLI အစစ်မှာဆိုရင် console.error (stderr) ကို သုံးပါ။
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
}
class Repository<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getAll(): readonly T[] {
return this.items;
}
find(predicate: (item: T) => boolean): T | undefined {
return this.items.find(predicate);
}
}
class TaskNotFoundError extends Error {
constructor(id: number) {
super(`Task #${id} not found`);
this.name = "TaskNotFoundError";
}
}
class TaskManager {
private repo = new Repository<Task>();
private nextId = 1;
addTask(title: string, priority: Task["priority"]): Task {
const task: Task = { id: this.nextId++, title, status: TaskStatus.Todo, priority };
this.repo.add(task);
return task;
}
updateStatus(id: number, status: TaskStatus): void {
const task = this.repo.find((t) => t.id === id);
if (!task) throw new TaskNotFoundError(id);
task.status = status;
}
getStats(): [total: number, done: number] {
const all = this.repo.getAll();
const done = all.filter((t) => t.status === TaskStatus.Done).length;
return [all.length, done];
}
}
const manager = new TaskManager();
manager.addTask("Learn generics", "high");
manager.addTask("Write tests", "medium");
manager.updateStatus(1, TaskStatus.Done);
const [total, done] = manager.getStats();
console.log(`Total: ${total}, Done: ${done}`);
try {
manager.updateStatus(99, TaskStatus.Done);
} catch (err) {
if (err instanceof TaskNotFoundError) console.log(`Error: ${err.message}`);
else throw err;
}
const tags = new Repository<string>();
tags.add("work");
tags.add("urgent");
console.log(`Tags: ${tags.getAll().join(", ")}`);Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Read-only view
getAll(): readonly T[] {Caller က list ကို ဖတ်၊ filter လုပ်လို့ရပေမယ့် push() ဒါမှမဟုတ် splice() လုပ်ရင် compile error ပါ။ Repository ရဲ့ array ကို အပြင်ကနေ မပြင်နိုင်တော့ပါဘူး။
- A named error type
class TaskNotFoundError extends Error {ကိုယ်ပိုင် error class ရှိတော့ catch ထဲမှာ "task မတွေ့တာလား၊ တခြား bug လား" ကို instanceof နဲ့ ခွဲနိုင်ပါတယ်။
- Composition with explicit <T>
private repo = new Repository<Task>();TaskManager က Repository ကို ပိုင်ထားပါတယ် (has-a)။ <Task> ကို မရေးရင် T က unknown ဖြစ်သွားပါမယ်။
- Throw instead of false
if (!task) throw new TaskNotFoundError(id);Narrowing က အတူတူပါပဲ၊ ဒါပေမယ့် miss ကို return value မဟုတ်ဘဲ error အဖြစ် ပို့ပါတယ်။ ဒီ line အောက်မှာ task က Task ပါ။
- Labeled tuple
getStats(): [total: number, done: number] {Element နှစ်ခု၊ အစီအစဉ် ပုံသေ။ const [total, done] = ... က position အလိုက် ခွဲယူတာဖြစ်ပြီး label နာမည်နဲ့ မဟုတ်ပါဘူး။
- Narrow the caught value
if (err instanceof TaskNotFoundError) console.log(`Error: ${err.message}`);Strict mode မှာ err ရဲ့ type က unknown ပါ။ instanceof နဲ့ စစ်ပြီးမှ .message ကို ဖတ်ပြီး မသိတဲ့ error တွေကို ပြန် throw လုပ်ပါတယ်။
Total: 2, Done: 1
Error: Task #99 not found
Tags: work, urgentProject တစ်ခုလုံးကို ပြန်ကြည့်ရအောင်
| Part | ထည့်ခဲ့တဲ့ TypeScript feature |
|---|---|
| 1. Setup | string enum, literal union, interface, indexed access type |
| 2. Class | private field, narrowing find(), boolean result, filter() |
| 3. Polish | generic class, composition, readonly array, labeled tuple, custom error |
ဆက်လုပ်ကြည့်ချင်ရင် tasks ကို JSON file ထဲ သိမ်းပြီး program ပြန်စတဲ့အခါ ပြန်ဖတ်ကြည့်ပါ။ File ကနေ ဖတ်တဲ့ data က unknown ဖြစ်လို့ async APIs lesson မှာ လေ့လာခဲ့တဲ့ zod schema နဲ့ validate လုပ်ပြီးမှ Repository ထဲ ထည့်ပါ။ Code များလာရင် Task type၊ Repository နဲ့ TaskManager ကို ESM module သုံးခုအဖြစ် ခွဲပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Repository pattern က backend code မှာ အရမ်းအသုံးများပါတယ်။ ORM library အချို့က entity တစ်ခုစီအတွက် generic Repository<Entity> တစ်ခုကို ပေးပါတယ်။ Team တွေက Repository<T> interface တစ်ခု ရေးပြီး implementation နှစ်ခု ထားလေ့ရှိပါတယ်။ Test အတွက် ဒီ lesson လို in-memory array နဲ့ တစ်ခု၊ production အတွက် database နဲ့ တစ်ခု ဖြစ်ပါတယ်။ Service class က interface ကိုပဲ မှီခိုလို့ test တွေက database မလိုဘဲ မြန်မြန် run နိုင်ပါတယ်။
Custom error class တွေကိုလည်း API layer မှာ HTTP status code နဲ့ တွဲလေ့ရှိပါတယ်။ ဥပမာ TaskNotFoundError က 404၊ ValidationError က 400 ဖြစ်ပါတယ်။ Tuple ကို ပြန်ပေးတဲ့ API ကိုလည်း နေ့တိုင်း သုံးနေပြီးသားပါ။ React ရဲ့ useState() က [value, setValue] ဆိုတဲ့ tuple ကို ပြန်ပေးလို့ နာမည်ကို ကိုယ်ကြိုက်သလို ပေးပြီး destructure လုပ်နိုင်တာပါ။ နောက်ပိုင်း getById() လို method လိုလာတဲ့အခါ team တွေက T extends { id: number } လို constraint ကို ထည့်ပါတယ်။ ဒါက ဒီ lesson ရဲ့ challenge အတိုင်းပါပဲ။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Type argument ကို ချန်ခဲ့တာ
private repo = new Repository(); လို့ ရေးရင် T က unknown ဖြစ်သွားပါတယ် (any လို့ ထင်တတ်ပေမယ့် မဟုတ်ပါ)။ add() က number တွေကိုပါ လက်ခံသွားပြီး find() ရလဒ်ကို သုံးတဲ့ နေရာတိုင်းမှာ error တွေ ပေါ်လာပါတယ်။ new Repository<Task>() လို့ ရေးပါ။
Tuple element အစီအစဉ် လွဲတာ
return [done, all.length]; လို့ မှားရေးရင်လည်း element နှစ်ခုလုံး number ဖြစ်လို့ compile ဖြစ်သွားပြီး "Total: 1, Done: 2" လို့ ထွက်ပါတယ်။ Label တွေက documentation ပဲ ဖြစ်ပြီး အစီအစဉ်ကို မစစ်ပေးပါဘူး။ Field သုံးခုထက် များလာရင် { total, done } လို object ကို ပြန်ပေးတာ ပိုလုံခြုံပါတယ်။
catch ထဲမှာ err.message ကို တန်းဖတ်တာ
Strict mode မှာ catch (err) ရဲ့ err က unknown ဖြစ်လို့ err.message က compile error ပါ။ (err as Error) နဲ့ ဖုံးမထားပါနဲ့။ ဘာမဆို throw လုပ်လို့ရလို့ instanceof နဲ့ စစ်ပြီး မသိတဲ့ error ကို ပြန် throw လုပ်ပါ။
Best Practices
ကောင်းမွန်တဲ့ အလေ့အကျင့်များ
- Generic ကို class နှစ်ခုမှာ logic တကယ် ထပ်နေမှ ထုတ်ပါ၊ "နောက်တစ်နေ့ လိုမလားမသိ" ဆိုပြီး ကြိုမထုတ်ပါနဲ့
- T ရဲ့ property ကို သုံးဖို့ လိုမှသာ extends နဲ့ constraint ထည့်ပါ
- Internal collection ကို ပြန်ပေးတဲ့အခါ readonly T[] ဒါမှမဟုတ် copy ကို ပြန်ပေးပါ
Mini challenge
id ရှိတဲ့ type တွေအတွက် IdRepository
Repository<T> က T အကြောင်း ဘာမှမသိလို့ getById() ကို မရေးနိုင်ပါဘူး။ T ကို { id: number } ရှိရမယ်လို့ constraint ပေးထားတဲ့ IdRepository<T> ကို ရေးပြီး Note type နဲ့ စမ်းကြည့်ပါ။
- class IdRepository<T extends { id: number }> လို constraint ပါရပါမယ်
- getById(id) က T | undefined ကို ပြန်ပေးပါ
- remove(id) က တကယ် ဖယ်ရှားခဲ့ရင်ပဲ true ပြန်ပေးပါ
- Note { id; text } နှစ်ခုထည့်ပြီး တစ်ခုကို နှစ်ခါ remove လုပ်ကြည့်ပါ
// TODO: constrain T so every item is guaranteed to have id: number
class IdRepository<T> {
private items: T[] = [];
add(item: T): void {
// TODO
}
getById(id: number): T | undefined {
// TODO: item.id only compiles once T is constrained
}
remove(id: number): boolean {
// TODO: filter it out, assign back, report whether the length changed
}
}
interface Note {
id: number;
text: string;
}
// TODO: create an IdRepository<Note>, add two notes, look one up, remove one twiceရလဒ်: "Call the bank" ကို ပြပြီး remove က true false ကို ပြန်ပေးကာ နောက်ဆုံးမှာ "Notes left: 1" ပေါ်ပါမယ်။ new IdRepository<string>() က compile error ဖြစ်ရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Constraint မပါရင် item.id မှာ "Property 'id' does not exist on type 'T'" error ရပါတယ်။ <T extends { id: number }> လို့ ရေးလိုက်ရင် T ဘာပဲဖြစ်ဖြစ် id ရှိတာ သေချာသွားပါတယ်။
အဖြေ ကြည့်ရန်
class IdRepository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getById(id: number): T | undefined {
return this.items.find((item) => item.id === id);
}
remove(id: number): boolean {
const before = this.items.length;
this.items = this.items.filter((item) => item.id !== id);
return this.items.length < before;
}
count(): number {
return this.items.length;
}
}
interface Note {
id: number;
text: string;
}
const notes = new IdRepository<Note>();
notes.add({ id: 1, text: "Buy milk" });
notes.add({ id: 2, text: "Call the bank" });
console.log(notes.getById(2)?.text);
console.log(notes.remove(1), notes.remove(1));
console.log(`Notes left: ${notes.count()}`);
// new IdRepository<string>(); // error: 'string' does not satisfy '{ id: number; }'Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Logic တူပြီး type ပဲကွာတဲ့ class တွေကို generic class တစ်ခုအဖြစ် ပေါင်းပါ
- ခန့်မှန်းစရာ မရှိတဲ့နေရာမှာ <Task> လို type argument ကို ရေးပါ၊ မဟုတ်ရင် T က unknown ဖြစ်ပါတယ်
- Composition က storage ကို ပြန်သုံးရင်း task rule တွေကို ကာကွယ်ပေးပါတယ်
- Labeled tuple က အစီအစဉ်ကို မစစ်ပေးပါ၊ catch ထဲက err ကို instanceof နဲ့ narrowing လုပ်ပါ
TypeScript Handbook — TypeScript