Skip to content
GitHub

Exclude<T,U>, Extract<T,U>, NonNullable<T>

ဒီဥပမာတွေအတွက် Union Type လေးတစ်ခုကို အရင်သတ်မှတ်ထားရအောင်။

index.ts
type Status = "pending" | "processing" | "success" | "error" | null | undefined;

Exclude<T, U>: Union ထဲက Type တွေကို ဖယ်ရှားခြင်း

Section titled “Exclude<T, U>: Union ထဲက Type တွေကို ဖယ်ရှားခြင်း”
  • ဘာလုပ်ပေးလဲ: Exclude<T, U> က T ဆိုတဲ့ Union Type ထဲက U နဲ့ တူညီတဲ့ Type တွေကို ဖယ်ထုတ်ပြီး Type အသစ်တစ်ခု လုပ်ပေးတယ်။
  • ဘယ်လို သုံးမလဲ: Exclude<Status, “processing” | “pending”>
  • ရလာမယ့် Type: “success” | “error” | null | undefined
  • ဘယ်အခါသုံးမလဲ:အခြေအနေ (Status) တွေ အများကြီး ရှိနေတယ်။ ဒါပေမယ့် တချို့အခြေအနေတွေကိုပဲ ဂရုစိုက်ချင်ပြီး ကျန်တာတွေကို လျစ်လျူရှုချင်တဲ့အခါမျိုးမှာ သုံးနိုင်တယ်။
index.ts
type FinalStatus = Exclude<Status, "pending" | "processing">;
let final: FinalStatus = "success"; // ဒါက အလုပ်လုပ်တယ်
// final = "pending"; // Error ပြလိမ့်မယ်။ 'pending' က FinalStatus Type မဟုတ်ဘူး။

Extract<T, U>: Union ထဲက Type တွေကို ရွေးချယ်ခြင်း

Section titled “Extract<T, U>: Union ထဲက Type တွေကို ရွေးချယ်ခြင်း”
  • ဘာလုပ်ပေးလဲ: Extract<T, U> က T ဆိုတဲ့ Union Type ထဲက U နဲ့ တူညီတဲ့ Type တွေကို ရွေးချယ်ပြီး Type အသစ်တစ်ခု လုပ်ပေးတယ်။
  • ဘယ်လို သုံးမလဲ: Extract<Status, “success” | “error”>
  • ရလာမယ့် Type: “success” | “error”
  • ဘယ်အခါသုံးမလဲ: ကျယ်ပြန့်တဲ့ Union Type တစ်ခုရှိနေတယ်။ ဒါပေမယ့် အဲဒီထဲက အစိတ်အပိုင်း တချို့ကိုပဲ သီးသန့် လိုချင်တဲ့အခါမျိုးမှာ သုံးနိုင်တယ်။
index.ts
type ResolvedStatus = Extract<Status, "success" | "error">;
let resolved: ResolvedStatus = "error"; // ဒါက အလုပ်လုပ်တယ်
// resolved = "pending"; // Error ပြလိမ့်မယ်။
// resolved = null; // Error ပြလိမ့်မယ်။
};

NonNullable<T>: null နှင့် undefined ကို ဖယ်ရှားခြင်း

Section titled “NonNullable<T>: null နှင့် undefined ကို ဖယ်ရှားခြင်း”
  • ဘာလုပ်ပေးလဲ: NonNullable<T> က T ဆိုတဲ့ Type ထဲက null နဲ့ undefined ကို ဖယ်ရှားပြီး Type အသစ်တစ်ခု လုပ်ပေးတယ်။
  • ဘယ်လို သုံးမလဲ: NonNullable<Status>
  • ရလာမယ့် Type: “pending” | “processing” | “success” | “error”
  • ဘယ်အခါသုံးမလဲ: တန်ဖိုးတစ်ခုက null ဒါမှမဟုတ် undefined ဖြစ်နိုင်တယ်။ ဒါပေမယ့် Code ထဲမှာ စစ်ဆေးပြီးနောက်ပိုင်း null ဒါမှမဟုတ် undefined မဟုတ်တော့ဘူးလို့ သေချာတဲ့အခါမျိုးမှာ အရမ်း အသုံးဝင်တယ်။
index.ts
let currentStatus: Status = "pending";
// ... တချို့ Logic တွေ ...
if (currentStatus !== null && currentStatus !== undefined) {
// ဒီ Block ထဲမှာဆိုရင် TypeScript က currentStatus ဟာ null ဒါမှမဟုတ် undefined မဟုတ်တော့ဘူးဆိုတာ သိနေပြီ။
// တခြား Function တစ်ခုကို ပို့ရင်လည်း Type ကို အတိအကျ သတ်မှတ်ပေးလို့ ရတယ်:
let activeStatus: NonNullable<Status> = currentStatus;
console.log(activeStatus.toUpperCase()); // toUpperCase() ကို စိတ်ချစွာ သုံးလို့ရပြီ။
};