Thuta Learning
TypeScript
ExercisesProgrammingအလယ်အလတ်

Practice Exercises - Set 2 (Intermediate & Advanced)

TypeScriptသင်ခန်းစာ 2845 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • kind property ပေါ်မှာ switch သုံးပြီး union ကို narrowing လုပ်ကာ never နဲ့ case အားလုံး ပါ/မပါ စစ်နိုင်ဖို့
  • LIFO အစီအစဉ်နဲ့ အလုပ်လုပ်ပြီး T | undefined ပြန်ပေးတဲ့ generic Stack<T> ကို ရေးနိုင်ဖို့
  • override keyword နဲ့ subclass method ကို ရေးပြီး super() စည်းမျဉ်းကို ရှင်းပြနိုင်ဖို့
  • value is string predicate ပါတဲ့ type guard ကို ရေးပြီး filter() နဲ့ unknown[] ကို narrowing လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Set 1 မှာ concept တစ်ခုချင်းစီကို သီးသန့် လက်ကျင့်ခဲ့ပါတယ်။ Set 2 မှာတော့ exercise တစ်ခုစီက intermediate နဲ့ advanced lesson တွေက concept နှစ်ခု သုံးခုကို ပေါင်းသုံးရပါတယ်။ ဥပမာ Shape exercise မှာ union type၊ literal type နဲ့ narrowing သုံးခုလုံး လိုပါတယ်။

ဒီအဆင့်မှာ compiler error တွေ ပိုပေါ်လာတာ ပုံမှန်ပါပဲ။ "Property 'radius' does not exist on type 'Shape'" လို message တွေက ဘာမှားလဲ ပြောပြနေတာပါ။ Warm-up ကို ဖတ်ပြီး exercise တစ်ခုစီကို မစခင် စက္ကန့်အနည်းငယ် ရပ်ပြီး "ဒီမှာ ဘယ် concept တွေ လိုမလဲ" လို့ အရင်မေးပါ။

Problem → Why → Solution

ပြဿနာ: narrowing မလုပ်ဘဲ variant field ကို ဖတ်တာ

Exercise 1 ကို ပထမဆုံး ကြိုးစားတဲ့အခါ shape.radius ကို တန်းဖတ်ချင်ကြပါတယ်။ Compiler က "Property 'radius' does not exist on type 'Shape'" လို့ ငြင်းပါတယ်။ Shape က square လည်း ဖြစ်နိုင်ပြီး square မှာ radius မရှိလို့ပါ။

Error ကို ပျောက်အောင် (shape as any).radius လို့ ရေးလိုက်ရင် compile ဖြစ်သွားပါတယ်။ ဒါပေမယ့် square တစ်ခုကို ပေးလိုက်ရင် undefined ** 2 ဖြစ်ပြီး NaN ပြန်ရပါတယ်။ Exception မတက်လို့ NaN က total ထဲ၊ invoice ထဲအထိ တိတ်တဆိတ် ရောက်သွားနိုင်ပါတယ်။

attempt.ts
function getArea(shape: Shape): number {
  return Math.PI * shape.radius ** 2;
  // Error: Property 'radius' does not exist on type 'Shape'.
}

function getAreaSilenced(shape: Shape): number {
  return Math.PI * (shape as any).radius ** 2; // a square gives NaN
}

Compiler က ဘာကြောင့် ငြင်းတာလဲ

Union type ပေါ်မှာ variant အားလုံးမှာ ရှိတဲ့ property (ဒီမှာ kind) ကိုပဲ ဖတ်ခွင့်ရှိပါတယ်။ shape.kind === "circle" ကို စစ်ပြီးမှ TypeScript က shape ကို circle variant အဖြစ် narrowing လုပ်ပြီး radius ကို ဖွင့်ပေးပါတယ်။ Error က bug မဟုတ်ပါဘူး၊ ဘယ် case ကို မစစ်ရသေးလဲ ပြောပြနေတာပါ။

Exercise လေးခုမှာ လိုမယ့် concept တွေ

Exercise လေးခုက မတူသလို ထင်ရပေမယ့် မေးခွန်း တစ်ခုတည်းကို ဖြေနေကြတာပါ။ "ဒီ value က တကယ် ဘာလဲ ဆိုတာ compiler ကို ဘယ်လို သက်သေပြမလဲ" ဆိုတာပါ။ kind စစ်တာ၊ undefined ဖြစ်နိုင်ကြောင်း ဝန်ခံတာ၊ override လို့ ကြေညာတာ၊ predicate ရေးတာ အားလုံးက ဒီသက်သေပြချက်ရဲ့ ပုံစံ အမျိုးမျိုးပါ။

Discriminated union နဲ့ never

Variant တိုင်းမှာ kind လို literal property တစ်ခု ရှိရင် switch (shape.kind) က case တစ်ခုစီထဲမှာ shape ကို variant တစ်ခုတည်းအဖြစ် narrowing လုပ်ပေးပါတယ်။ default ထဲမှာ const unhandled: never = shape; လို့ ရေးထားရင် နောက်ပိုင်း triangle variant အသစ် ထည့်တဲ့အခါ case မထည့်ရသေးသရွေ့ compile error ပေါ်ပါတယ်။

T | undefined ပြန်ပေးတဲ့ generic class

Stack<T> က item type ကို မသိဘဲ push၊ pop၊ peek လုပ်ပါတယ်။ Stack အလွတ်ဖြစ်နိုင်လို့ pop() နဲ့ peek() က T | undefined ပြန်ရပါမယ်။ Array.pop() က T | undefined ကို ပြန်ပေးပြီးသားပါ။ ဒါပေမယ့် this.items[this.items.length - 1] ကတော့ default setting မှာ T လို့ပဲ type ရလို့ return type ကို ကိုယ်တိုင် T | undefined လို့ ရေးထားပါ။

Inheritance နဲ့ override

class Dog extends Animal က Animal ရဲ့ method အားလုံးကို အမွေဆက်ခံပါတယ်။ override makeSound() က parent method ကို အစားထိုးပြီး override keyword ကြောင့် parent မှာ ဒီနာမည်နဲ့ method မရှိရင် (ဥပမာ typo) error ရပါတယ်။ noImplicitOverride ဖွင့်ထားရင် keyword က မဖြစ်မနေ လိုပါတယ်။ Subclass မှာ constructor ရေးရင် this ကို မသုံးခင် super() ကို အရင်ခေါ်ရပါမယ်။

Type predicate (value is string)

function isString(value: unknown): value is string က "true ပြန်ရင် value က string ပါ" လို့ compiler ကို ကတိပေးတာပါ။ ဒါကြောင့် mixed.filter(isString) က string[] ဖြစ်ပါတယ်။ Return type ကို boolean လို့ ရေးရင် ဒီကတိ ပျောက်ပြီး ရလဒ်က unknown[] ပဲ ဖြစ်ပါတယ်။ TypeScript 5.5 ကစပြီး return type မရေးထားတဲ့ ရိုးရှင်းတဲ့ function တွေအတွက် predicate ကို ခန့်မှန်းပေးနိုင်ပေမယ့် : boolean လို့ ရေးလိုက်ရင် အဲဒီ ခန့်မှန်းချက် ပိတ်သွားပါတယ်။

ExerciseConceptအဓိက syntax
1. ShapeNarrowingswitch (shape.kind)
2. Stack<T>Genericspop(): T | undefined
3. DogInheritanceoverride makeSound()
4. isStringType guardvalue is string
Mental model: compiler ကို သက်သေပြပါ
  1. kind ကိုစစ်ပြီးမှ variant field ဖတ်
  2. အလွတ်ဖြစ်နိုင်ရင် T | undefined
  3. Parent ကိုအစားထိုးရင် override ရေး
  4. Runtime check ကို predicate နဲ့ ထုပ်

Exercise လေးခုလုံးမှာ pattern က အတူတူပါ။ Runtime check တစ်ခုခု လုပ်ပြီး အဲဒီ check ကို compiler နားလည်တဲ့ ပုံစံနဲ့ ရေးပါ။

အခြေခံ ပုံစံ

typescript
switch (value.kind) {
  case "a": return handleA(value);   // value narrowed to the "a" variant
  default: { const rest: never = value; throw new Error(String(rest)); }
}

class Box<T> { take(): T | undefined { /* may be empty */ } }

class Child extends Parent { override method(): R { /* ... */ } }

function isType(v: unknown): v is Type { return /* runtime check */; }

Narrowing switch နဲ့ never check၊ undefined ပြန်နိုင်တဲ့ generic method၊ override လုပ်တဲ့ subclass နဲ့ type predicate ဆိုတဲ့ ပုံစံလေးမျိုးပါ။

ဖြေပြီးသား warm-up: payment၊ queue၊ notifier

ဒီ warm-up လေးပိုင်းက exercise လေးခုနဲ့ concept တူပေမယ့် data မတူပါဘူး။ Payment union၊ Queue<T> (Stack နဲ့ ဆန့်ကျင်ဘက် FIFO)၊ Notifier/EmailNotifier နဲ့ isNumber guard ပါ။ isNumber က NaN ကိုပါ ဖယ်ထုတ်တာကို သတိထားကြည့်ပါ။ typeof NaN က "number" ဖြစ်လို့ပါ။

warm-up.ts
// Warm-up 1: a discriminated union, narrowed with switch
type Payment =
  | { kind: "card"; amount: number; feePercent: number }
  | { kind: "cash"; amount: number };

function totalCharge(p: Payment): number {
  switch (p.kind) {
    case "card":
      return p.amount + (p.amount * p.feePercent) / 100;
    case "cash":
      return p.amount;
  }
}

// Warm-up 2: a generic queue (first in, first out)
class Queue<T> {
  private items: T[] = [];

  enqueue(item: T): void {
    this.items.push(item);
  }

  dequeue(): T | undefined {
    return this.items.shift();
  }

  get size(): number {
    return this.items.length;
  }
}

// Warm-up 3: overriding a method in a subclass
class Notifier {
  send(message: string): string {
    return `Notice: ${message}`;
  }
}

class EmailNotifier extends Notifier {
  override send(message: string): string {
    return `Email -> ${super.send(message)}`;
  }
}

// Warm-up 4: a user-defined type guard
function isNumber(value: unknown): value is number {
  return typeof value === "number" && !Number.isNaN(value);
}

console.log(totalCharge({ kind: "card", amount: 200, feePercent: 3 }));

const queue = new Queue<string>();
queue.enqueue("first");
queue.enqueue("second");
console.log(queue.dequeue(), queue.size);

const notifier: Notifier = new EmailNotifier();
console.log(notifier.send("build finished"));

const raw: unknown[] = [10, "11", 12, NaN];
console.log(raw.filter(isNumber));

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Narrowed per casereturn p.amount + (p.amount * p.feePercent) / 100;

    case "card" ထဲမှာ p က card variant ဖြစ်လို့ feePercent ကို ဖတ်လို့ရပါတယ်။ case "cash" ထဲမှာ p.feePercent လို့ ရေးရင် error ပါ။ 200 + 6 = 206။

  2. May be emptydequeue(): T | undefined {

    shift() က ရှေ့ဆုံး item ကို ထုတ်ပြီး queue အလွတ်ဆိုရင် undefined ပြန်ပေးပါတယ်။ ဒါကြောင့် "first" ထွက်ပြီး size က 1 ကျန်ပါတယ်။

  3. Override and reuse the parentoverride send(message: string): string {

    Notifier type နဲ့ ကြေညာထားပေမယ့် runtime object က EmailNotifier ဖြစ်လို့ subclass method ကို ခေါ်ပါတယ်။ super.send() က parent ရဲ့ စာသားကို ပြန်သုံးပါတယ်။

  4. Type predicatefunction isNumber(value: unknown): value is number {

    filter(isNumber) ရဲ့ ရလဒ်က number[] ဖြစ်ပါတယ်။ "11" (string) နဲ့ NaN ကို ဖယ်လို့ [ 10, 12 ] ပဲ ကျန်ပါတယ်။

You should see
206
first 1
Email -> Notice: build finished
[ 10, 12 ]

Exercise တွေကို ဘယ်လို စမ်းမလဲ

  • getArea(): radius 1 ဆိုရင် 3.14 (toFixed(2))၊ side 3 ဆိုရင် 9 ရရမယ်
  • Stack<T>: 1, 2, 3 push ပြီး pop() က 3၊ peek() က 2 ပြန်ရမယ်၊ peek() က item မဖယ်ရ
  • Dog: const pet: Animal = new Dog(); pet.makeSound() က "Woof" ဖြစ်ရမယ်
  • isString: [1, "two", 3, "four"] ကနေ [ 'two', 'four' ] ရပြီး ရလဒ်ရဲ့ type က string[] ဖြစ်ရမယ်

Type ကိုလည်း စစ်ပါ

Editor မှာ strings variable ပေါ် mouse တင်ကြည့်ပါ။ unknown[] လို့ ပြရင် isString ရဲ့ return type က predicate မဟုတ်သေးပါဘူး။ Output မှန်နေရင်တောင် type မှားနေနိုင်ပါတယ်။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Discriminated union တွေက app state နဲ့ message တွေမှာ နေရာတိုင်း ပေါ်ပါတယ်။ Redux action တွေ၊ { status: "loading" } | { status: "success"; data } | { status: "error"; error } လို request state တွေ၊ WebSocket message type တွေ အားလုံး ဒီ pattern ပါ။ never check က variant အသစ်ထည့်တဲ့အခါ ကိုင်တွယ်ဖို့ မေ့ကျန်ခဲ့တဲ့ နေရာတိုင်းကို compile time မှာ ပြပေးပါတယ်။

Stack ကို undo/redo history၊ browser ရဲ့ back button၊ bracket စစ်တဲ့ parser တွေမှာ သုံးပါတယ်။ Type guard တွေကတော့ JSON.parse() ဒါမှမဟုတ် fetch() ကနေ ရလာတဲ့ unknown data ကို စစ်ဖို့ အဓိကပါ။ Field များတဲ့ data ဆိုရင် guard ကို ကိုယ်တိုင်ရေးမယ့်အစား zod လို schema library ကို သုံးလေ့ရှိပါတယ်။ Inheritance ကိုတော့ framework class တွေ (Error subclass တွေလို) မှာ အသုံးများပြီး app code မှာ composition ကို ပိုရွေးလေ့ရှိပါတယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

Type guard ကို : boolean လို့ ရေးတာ

function isString(value: unknown): boolean လို့ ရေးရင် runtime မှာ မှန်မှန် အလုပ်လုပ်ပေမယ့် mixed.filter(isString) ရဲ့ type က unknown[] ဖြစ်နေဆဲပါ။ ရလဒ်ပေါ်မှာ .toUpperCase() ခေါ်ရင် error ရပါတယ်။ value is string လို့ ရေးပါ။

peek() ထဲမှာ pop() ကို ခေါ်တာ

return this.items.pop(); လို့ peek() ကို ရေးရင် type မှန်ပေမယ့် peek() ခေါ်တိုင်း item တစ်ခု ပျောက်သွားပါတယ်။ peek() က this.items[this.items.length - 1] ကို ဖတ်ရုံပဲ လုပ်ရပါမယ်။

Subclass constructor မှာ super() မေ့တာ

Dog ထဲမှာ name ကို သိမ်းဖို့ constructor ထည့်ပြီး super() မခေါ်ရင် "Constructors for derived classes must contain a 'super' call" error ရပါတယ်။ super() မခေါ်ခင် this.name လို့ ရေးရင်လည်း error ပါ။ super(...) ကို ပထမဆုံး ခေါ်ပါ။

Union error ကို as any နဲ့ ဖုံးတာ

(shape as any).radius က compile error ကို ပျောက်စေပေမယ့် bug ကို မပျောက်စေပါဘူး။ Square ဝင်လာတဲ့အခါ NaN ကို တိတ်တဆိတ် ပြန်ပေးပါတယ်။ Assertion ထည့်ချင်စိတ်ပေါ်လာရင် "ဘယ် check ကို ကျော်နေလဲ" လို့ မေးပြီး အဲဒီ check ကို ရေးပါ။

Best Practices

ကောင်းမွန်တဲ့ အလေ့အကျင့်များ

  • tsconfig မှာ noImplicitOverride ကို ဖွင့်ထားရင် override မရေးမိတဲ့ method တွေကို compiler က ပြပေးပါတယ်
  • Type guard ထဲမှာ check တစ်ခုထက် ပိုလိုရင် (ဥပမာ NaN) guard ကို တစ်နေရာတည်းမှာ ရေးပြီး ပြန်သုံးပါ
  • Union variant အသစ်ထည့်တိုင်း never check ပါတဲ့ switch တွေကို compiler ကိုယ်တိုင် ရှာပေးပါစေ

Mini challenge

Practice Set 2: exercise လေးခု

Warm-up ကို မကြည့်ဘဲ TODO တွေကို ဖြည့်ပါ။ Exercise 1 က Shape area၊ 2 က Stack<T>၊ 3 က Dog override၊ 4 က isString type guard ပါ။ Bonus အနေနဲ့ Stack မှာ isEmpty() ထည့်ပါ။

  • getArea() က switch (shape.kind) နဲ့ narrowing လုပ်ပြီး default မှာ never check ပါရပါမယ်
  • Stack<T> ရဲ့ pop() နဲ့ peek() က LIFO အစီအစဉ်အတိုင်း T | undefined ပြန်ပေးရပါမယ်
  • Dog က override keyword နဲ့ makeSound() ကို "Woof" ပြန်ပေးရပါမယ်
  • isString ရဲ့ return type က value is string ဖြစ်ပြီး filter ရလဒ်က string[] ဖြစ်ရပါမယ်
practice-2.ts
// Exercise 1
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function getArea(shape: Shape): number {
  // TODO: switch on shape.kind; add a never check in default
}

// Exercise 2
class Stack<T> {
  private items: T[] = [];
  // TODO: push(item: T): void
  // TODO: pop(): T | undefined   (last in, first out)
  // TODO: peek(): T | undefined  (read the top, do not remove it)
  // TODO (bonus): isEmpty(): boolean
}

// Exercise 3
class Animal {
  makeSound(): string {
    return "...";
  }
}
// TODO: class Dog extends Animal, overriding makeSound() to return "Woof"

// Exercise 4
// TODO: function isString(value: unknown): value is string

ရလဒ်: 3.14၊ 9၊ 3 2 false၊ Woof နဲ့ [ 'two', 'four' ] ကို line တစ်ကြောင်းစီ ပြပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

pop() အတွက် this.items.pop() ကို တိုက်ရိုက် ပြန်ပေးလို့ ရပါတယ်။ peek() အတွက် နောက်ဆုံး index ကို ဖတ်ပါ။ isString ကတော့ typeof value === "string" ကို ပြန်ပေးရုံပါပဲ၊ အရေးကြီးတာက return type ပါ။

အဖြေ ကြည့်ရန်
practice-2.ts
// Exercise 1
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    default: {
      const unhandled: never = shape;
      throw new Error(`Unknown shape: ${JSON.stringify(unhandled)}`);
    }
  }
}

// Exercise 2
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }

  isEmpty(): boolean {
    return this.items.length === 0;
  }
}

// Exercise 3
class Animal {
  makeSound(): string {
    return "...";
  }
}

class Dog extends Animal {
  override makeSound(): string {
    return "Woof";
  }
}

// Exercise 4
function isString(value: unknown): value is string {
  return typeof value === "string";
}

console.log(getArea({ kind: "circle", radius: 1 }).toFixed(2));
console.log(getArea({ kind: "square", side: 3 }));

const stack = new Stack<number>();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop(), stack.peek(), stack.isEmpty());

const pet: Animal = new Dog();
console.log(pet.makeSound());

const mixed: unknown[] = [1, "two", 3, "four"];
const strings: string[] = mixed.filter(isString);
console.log(strings);

Quick Quiz 1 / 3

Stack<number> မှာ 1, 2, 3 ကို push လုပ်ပြီး pop() တစ်ခါ ခေါ်ပါတယ်။ ပြီးမှ peek() က ဘာပြန်ပေးမလဲ။

Quick Quiz 2 / 3

function isString(value: unknown): boolean { return typeof value === "string"; } ဆိုရင် mixed.filter(isString) (mixed: unknown[]) ရဲ့ type က ဘာလဲ။

Quick Quiz 3 / 3

Shape ထဲကို { kind: "triangle"; base: number; height: number } ထပ်ထည့်ပြီး getArea() ကို မပြင်ရသေးပါဘူး။ Solution ရဲ့ never check ကြောင့် ဘာဖြစ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Union ရဲ့ variant field ကို kind စစ်ပြီးမှ ဖတ်ပြီး default မှာ never check ထည့်ပါ
  • အလွတ်ဖြစ်နိုင်တဲ့ generic method တွေက T | undefined ပြန်ပေးရပါမယ်
  • Parent method ကို အစားထိုးရင် override ရေးပြီး subclass constructor မှာ super() ကို အရင်ခေါ်ပါ
  • Type guard ရဲ့ return type က value is Type ဖြစ်ရမယ်၊ boolean ဆိုရင် narrowing မရပါ

TypeScript Handbook — TypeScript

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Practice Exercises - Set 2 (Intermediate & Advanced) | Thuta Learning