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

Union Types & Aliases

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

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

  • Shape အများအပြား ဖြစ်နိုင်တဲ့ value တွေအတွက် | နဲ့ union type တွေ ရေးနိုင်ဖို့
  • Union, object shape ဒါမှမဟုတ် function type တစ်ခုကို type alias နဲ့ ပြန်သုံးလို့ရတဲ့ နာမည် ပေးနိုင်ဖို့
  • Narrowing မလုပ်ခင် union value ပေါ်မှာ TypeScript က ဘယ် operation တွေကို ခွင့်ပြုမလဲ ကြိုမှန်းနိုင်ဖို့
  • Alias ဆိုတာ နာမည်တစ်ခုသာ ဖြစ်ပြီး သီးခြား type အသစ် မဟုတ်ဘူးဆိုတာ သိဖို့

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

Union နဲ့ alias ကို ရိုးရိုးလေး ရှင်းရရင်

Union type က "ဒီ value က ဒီထဲက တစ်ခုခုပဲ" လို့ ပြောတာပါ။ string | number ဆိုရင် value က string ဒါမှမဟုတ် number ဖြစ်ပြီး တခြား ဘာမှ မဖြစ်နိုင်ပါဘူး။ Pipe character | နဲ့ ရေးပြီး "or" လို့ ဖတ်လို့ ရပါတယ်။

Type alias ကတော့ type keyword နဲ့ type တစ်ခုကို နာမည်ပေးတာပါ။ type ProductId = string | number လို့ တစ်ခါ ရေးထားပြီးရင် union အပြည့်အစုံကို ထပ်ခါထပ်ခါ မရေးတော့ဘဲ နေရာတိုင်းမှာ ProductId ကိုပဲ သုံးလို့ ရပါတယ်။ Alias တွေက ရှည်လျားတဲ့ type တွေကို ဖတ်ရလွယ်စေပြီး သုံးထားတဲ့ နေရာအားလုံးကို တစ်ပြေးညီ ဖြစ်နေစေပါတယ်။

Problem → Why → Solution

ပြဿနာ: type တစ်ခုက ကျဉ်းလွန်းတယ်၊ any က ကျယ်လွန်းတယ်

Online shop တစ်ခုမှာ product ဟောင်းတွေရဲ့ ID က number ဖြစ်ပြီး product အသစ်တွေရဲ့ ID က "sku-2048" လို string ဖြစ်တယ် ဆိုပါစို့။ Parameter ကို number လို့ type ပေးရင် ID အသစ်တွေကို ငြင်းပါတယ်။ any လို့ ပေးရင်တော့ undefined နဲ့ object တွေ အပါအဝင် အကုန်လုံးကို လက်ခံသွားပါတယ်။ Developer တစ်ယောက်က string | number ကို function ရှစ်ခုထဲ copy ကူးထည့်ထားပြီး တတိယ ID format တစ်ခု ရောက်လာတဲ့အခါ copy ရှစ်ခုထဲက နှစ်ခုကို ပြင်ဖို့ မေ့သွားပါတယ်။

product-ids.ts
function findProduct(id: number) { /* ... */ }
findProduct("sku-2048"); // error: string is not assignable to number

function removeProduct(id: any) { /* ... */ }
removeProduct({ id: 7 }); // compiles, but is clearly wrong

ဘာ လိုအပ်နေတာလဲ

Type တစ်ခုတည်းက ကျဉ်းလွန်းပြီး any က ကျယ်လွန်းပါတယ်။ ခွင့်ပြုတဲ့ type တွေကို အတိအကျ စာရင်းပြုနိုင်တဲ့ နည်းလမ်းတစ်ခုနဲ့ အဲဒီ စာရင်းကို တစ်ခါပဲ ရေးပြီး function တိုင်းက definition တစ်ခုတည်းကို မျှသုံးနိုင်တဲ့ နည်းလမ်းတစ်ခု လိုအပ်ပါတယ်။

အဓိက concept: value အစု၊ ခွင့်ပြုတဲ့ operation တွေနဲ့ နာမည်

Union A | B က A ဒါမှမဟုတ် B ဖြစ်တဲ့ value ကို ဖော်ပြပါတယ်။ ခွင့်ပြုတဲ့ value အစုတွေကို ပေါင်းထားတာလို့ မြင်ကြည့်ပါ: string | number က string တိုင်းနဲ့ number တိုင်းကို လက်ခံပါတယ်။ Literal type တွေ အပါအဝင် ဘယ် type မဆို ပေါင်းလို့ရပါတယ်: type Status = "idle" | "loading" | "done" က string သုံးခုကိုပဲ အတိအကျ လက်ခံပါတယ်။ strictNullChecks ဖွင့်ထားတဲ့အခါ string | null လို union ထဲ null ဒါမှမဟုတ် undefined ထည့်တာက value မရှိနိုင်ဘူးဆိုတာကို TypeScript မှာ ဖော်ပြတဲ့ နည်းပါ။

တစ်ဖက်ခြမ်းက အရေးကြီးပါတယ်။ Union value ထဲမှာ ဘယ် member ရှိနေလဲ TypeScript မသိတာကြောင့် member တိုင်းအတွက် valid ဖြစ်တဲ့ operation တွေကိုပဲ ခွင့်ပြုပါတယ်။ string | number ပေါ်မှာ type နှစ်ခုလုံးမှာ ရှိတဲ့ toString() ကို ခေါ်လို့ရပေမယ့် string မှာပဲ ရှိတဲ့ toUpperCase() ကိုတော့ မခေါ်ရပါဘူး။ Union ကျယ်လေ တိုက်ရိုက် ခွင့်ပြုတဲ့ operation နည်းလေပါပဲ။ မသုံးခင် မှန်ကန်တဲ့ member ကို ရွေးထုတ်တာကို narrowing လို့ ခေါ်ပြီး နောက် lesson မှာ အသေးစိတ် လေ့လာပါမယ်။

Value ရဲ့ typeNarrowing မလုပ်ဘဲ ရတာNarrowing မလုပ်ဘဲ မရတာ
string | numbertoString(), "ID: " + valuetoUpperCase(), toFixed(2)
{ name; age } | { name; email }.name (နှစ်ခုလုံးမှာ ရှိတယ်).age, .email
"S" | "M" | "L"=== နဲ့ နှိုင်းယှဉ်တာ၊ string အဖြစ် သုံးတာ"XL" ကို assign လုပ်တာ

Type alias က type တစ်ခုကို နာမည်ပေးပါတယ်: type Name = SomeType။ ညာဘက်မှာ union, object shape, tuple, function type ဘာမဆို ဖြစ်နိုင်ပါတယ်။ Alias တွေက type အသစ် မဆောက်ပါဘူး၊ နာမည်တွေ သက်သက်ပါ။ type UserId = string နဲ့ type OrderId = string နှစ်ခုလုံးက string ပဲ ဖြစ်တာကြောင့် UserId လိုတဲ့ နေရာမှာ OrderId ကို ပေးလိုက်ရင်လည်း compiler က ကျေကျေနပ်နပ် လက်ခံပါတယ်။ Alias ကို ဖတ်ရလွယ်အောင်နဲ့ နေရာတစ်ခုတည်းမှာ ပြင်လို့ရအောင် သုံးပါ၊ base type တူတဲ့ value တွေကို ခွဲခြားဖို့ မသုံးပါနဲ့။

text
Write the union once, share it everywhere
-----------------------------------------
type ProductId = string | number;      <- the union is written once

function findProduct(id: ProductId)    <- every function refers to it
function removeProduct(id: ProductId)
function logProduct(id: ProductId)

Change the alias later:
type ProductId = string | number | bigint
  -> all three functions pick up the new member automatically
မှတ်ထားရမယ့် ပုံစံ
  1. ခွင့်ပြုတဲ့ type တွေ စာရင်းပြု: A | B
  2. တစ်ခါ နာမည်ပေး: type Alias = A | B
  3. Member တိုင်းမှာ ရှိတာကိုပဲ သုံး
  4. Member သီးသန့် အပိုင်းအတွက် narrow လုပ်

Union က value ဖြစ်နိုင်တာကို ချဲ့ပေးပြီး မစစ်ရသေးသမျှ လုပ်လို့ရတာကို ကျဉ်းစေပါတယ်။

အထွေထွေ ပုံစံ

typescript
type Alias = TypeA | TypeB;              // union of types
type Choice = "first" | "second";        // union of literal values
type MaybeValue = Value | null;          // a value that may be missing
type Shape = { field: Type };            // alias for an object shape
type Handler = (input: Input) => Output; // alias for a function type

function name(param: Alias): Result { /* ... */ }

| က type တွေကို "or" နဲ့ ပေါင်းပြီး type Name = ... က ဘယ် type ကိုမဆို နာမည်ပေးပါတယ်။ ပြီးရင် alias ကို တခြား type တစ်ခုလိုပဲ annotation မှာ သုံးပါ။

ID format နှစ်မျိုးကို လက်ခံတဲ့ function

အောက်က example က union ကို alias နဲ့ နာမည်ပေးပြီး ID format နှစ်မျိုးလုံးကို လက်ခံတဲ့ function တစ်ခုမှာ သုံးပါတယ်။ console.log ကို ခေါ်တိုင်း line အသစ်တစ်ကြောင်း ထွက်တာကြောင့် output က line နှစ်ကြောင်း ဖြစ်ပါတယ်။

typescript
// Type Alias for a complex type
type StringOrNumber = string | number;

function printId(id: StringOrNumber) {
  console.log("Your ID is: " + id);
}

printId(101);
printId("abc-101");

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

  1. Line 2type StringOrNumber = string | number;

    Union string | number ကို StringOrNumber ဆိုတဲ့ နာမည်ပေးပါတယ်။ Runtime မှာ ဒီ line ဘာမှ မကျန်ပါဘူး။

  2. Line 4function printId(id: StringOrNumber) {

    Parameter က alias ကို သုံးတာကြောင့် string ရော number ရော လက်ခံပါတယ်။

  3. Line 5console.log("Your ID is: " + id);

    String နဲ့ + လုပ်တာက member နှစ်ခုလုံးအတွက် valid ဖြစ်ပါတယ် (number ကို စာသားအဖြစ် ပြောင်းပေးပါတယ်)၊ ဒါကြောင့် narrowing မလိုပါဘူး။ id.toUpperCase() ဆိုရင်တော့ error တက်ပါမယ်။

  4. Lines 8-9printId("abc-101");

    printId(101) နဲ့ printId("abc-101") နှစ်ခုလုံး compile ဖြစ်ပါတယ်။ printId(true) ဆိုရင်တော့ boolean က union ထဲမှာ မပါတာကြောင့် compile error ဖြစ်ပါမယ်။

You should see
Your ID is: 101
Your ID is: abc-101

Object shape တွေရဲ့ union

Union member တွေက object type တွေ ဖြစ်လည်း စည်းမျဉ်း တူတူပါပဲ: member အားလုံးမှာ ရှိတဲ့ property ကိုပဲ တိုက်ရိုက် ဖတ်လို့ ရပါတယ်။ အောက်က example မှာ method က member နှစ်ခုလုံးမှာ ရှိပေမယ့် last4 က card payment မှာပဲ ရှိပါတယ်။ method ကို စစ်ပြီး last4 ဆီ ရောက်အောင် လုပ်တဲ့ discriminated union pattern ကို နောက် lesson မှာ လေ့လာပါမယ်။

payment.ts
type CardPayment = { method: "card"; last4: string };
type CashPayment = { method: "cash" };
type Payment = CardPayment | CashPayment;

function describe(p: Payment): string {
  // p.method exists on both members, so this is allowed.
  // p.last4 would be an error: CashPayment has no last4.
  return `Paid by ${p.method}`;
}

console.log(describe({ method: "card", last4: "4242" })); // Paid by card
console.log(describe({ method: "cash" })); // Paid by cash
Typeအဓိပ္ပာယ်
(string | number)[]string နဲ့ number ရောနိုင်တဲ့ array တစ်ခု: [1, "two", 3]
string[] | number[]string ချည်းပဲ array ဒါမှမဟုတ် number ချည်းပဲ array
string | number[]string တစ်ခု ဒါမှမဟုတ် number array တစ်ခု

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

လက်တွေ့ project: UI component props နဲ့ API data

Frontend code မှာ literal union တွေကို နေရာတိုင်းမှာ တွေ့ရပါတယ်: button size "sm" | "md" | "lg"၊ theme "light" | "dark" | "system" စသဖြင့်ပါ။ Component ကို သုံးသူက "medium" လို့ စာလုံးပေါင်းမှားရင် browser ထဲ ရောက်မှ မဟုတ်ဘဲ editor ထဲမှာတင် အနီရောင် မျဉ်း မြင်ရပါတယ်။ Backend မှာတော့ deletedAt: Date | null လို nullable column တွေနဲ့ callback တွေအတွက် function type alias တွေကို မကြာခဏ တွေ့ရပါတယ်။ Props type တစ်ခုလုံးကို alias တစ်ခုအဖြစ် နာမည်ပေးထားတာကြောင့် component နဲ့ test တွေက definition တစ်ခုတည်းကို မျှသုံးပါတယ်:

button.ts
type ButtonSize = "sm" | "md" | "lg";
type ClickHandler = (label: string) => void;
type ButtonProps = {
  label: string;
  size?: ButtonSize;
  onClick: ClickHandler;
};

function renderButton(props: ButtonProps): string {
  const size = props.size ?? "md";
  return `<button class="btn-${size}">${props.label}</button>`;
}

console.log(renderButton({ label: "Save", onClick: () => {} }));
// renderButton({ label: "Save", size: "medium", ... }) would not compile

API response တွေမှာလည်း pattern တူတူကို တွေ့ရပါတယ်။ Request တစ်ခုရဲ့ state ကို type LoadState = "idle" | "loading" | "success" | "error" လို့ ကြေညာထားရင် UI code တိုင်းက ဖြစ်နိုင်တဲ့ state လေးခုကိုပဲ ကိုင်တွယ်ရမှန်း သိပါတယ်။ Product team က "cancelled" ဆိုတဲ့ state အသစ် ထည့်ချင်တဲ့နေ့မှာ alias တစ်နေရာတည်းကို ပြင်လိုက်ရုံနဲ့ အဲဒီ type ကို သုံးတဲ့ file အားလုံးက ပြောင်းလဲမှုကို ချက်ချင်း မြင်ရပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားများ

1. Alias က ID တွေကို ခွဲခြားပေးမယ်လို့ ထင်တာ

type UserId = string နဲ့ type OrderId = string ကို ကြေညာထားပြီး cancelOrder(id: OrderId) ကို user ID နဲ့ ခေါ်မိရင် compiler က ဘာမှ မပြောပါဘူး၊ နှစ်ခုလုံးက string ပဲ ဖြစ်လို့ပါ။ ဒီလို ရောထွေးမှုကို တကယ် တားချင်ရင် branded type လို နည်းလမ်း သီးသန့် လိုပါတယ်၊ ရိုးရိုး alias က မလုံလောက်ပါဘူး။

2. Member တစ်ခုမှာပဲ ရှိတဲ့ method ကို as နဲ့ အတင်းခေါ်တာ

string | number value ပေါ်မှာ toUpperCase() က error ပေးတဲ့အခါ (id as string).toUpperCase() လို့ ပြင်လိုက်ချင်စိတ် ပေါ်လာပါတယ်။ ဒါက compiler ကို နှုတ်ပိတ်လိုက်ရုံပါ၊ id က 101 ဖြစ်တဲ့နေ့မှာ runtime မှာ TypeError နဲ့ crash ဖြစ်ပါမယ်။ Member တစ်ခုချင်းစီကို ကိုင်တွယ်ဖို့ narrowing ကို သုံးပါ။

3. Array type တွေမှာ ကွင်း မေ့တာ

string | number[] က "string တစ်ခု ဒါမှမဟုတ် number array" ဖြစ်ပြီး "string ရော number ရော ပါတဲ့ array" မဟုတ်ပါဘူး။ ရောနိုင်တဲ့ array လိုချင်ရင် (string | number)[] လို့ ကွင်းနဲ့ ရေးပါ။

Best Practices

အကောင်းဆုံး လုပ်ထုံးများ

  • Function နှစ်ခုထက်ပိုပြီး union တစ်ခုတည်းကို သုံးလာရင် alias တစ်ခု ပေးပါ။
  • Option စာရင်း ပုံသေ ဖြစ်တဲ့အခါ string ကျယ်ကျယ်အစား literal union ကို ရွေးပါ။
  • Value မရှိနိုင်ရင် | null ဒါမှမဟုတ် | undefined ကို type ထဲမှာ ရှင်းရှင်းလင်းလင်း ထည့်ပါ။
  • Union ကို any နဲ့ ဒါမှမဟုတ် as နဲ့ ကျော်မသွားပါနဲ့၊ narrowing ကို သုံးပါ။
  • Alias နာမည်ကို ဘာဖြစ်လဲ (StringOrNumber) ထက် ဘာအတွက်လဲ (ProductId) နဲ့ ပေးပါ။

Mini challenge

T-shirt order line တွေ

Literal union, nullable field နဲ့ object type alias တွေကို သုံးပြီး online shop ရဲ့ order line တွေကို model လုပ်ကာ line တစ်ခုစီရဲ့ စုစုပေါင်း ဈေးနှုန်းကို print ထုတ်ပါ။

  • type Size = "S" | "M" | "L" | "XL" ကို ကြေညာပါ။
  • Size တစ်ခုစီအတွက် number property ပါတဲ့ type PriceTable ကို ကြေညာပါ။
  • item, size, quantity နဲ့ giftNote: string | null ပါတဲ့ type OrderLine ကို ကြေညာပါ။
  • lineTotal(line, table) က table[line.size] * line.quantity ကို ပြန်ပေးရပါမယ်။
  • describeLine(line) က gift note မရှိရင် "no gift note" ကို ?? နဲ့ ပြရပါမယ်။
order-lines.ts
// TODO: type Size = four literal sizes
// TODO: type PriceTable = one number property per size
// TODO: type OrderLine = { item, size, quantity, giftNote (string or null) }

function lineTotal(line: OrderLine, table: PriceTable): number {
  // TODO: look up the price for line.size and multiply by quantity
  return 0;
}

function describeLine(line: OrderLine): string {
  // TODO: "2 x T-shirt (M) = $18, no gift note"
  return "";
}

// TODO: create two order lines and print describeLine() for each

ရလဒ်: "2 x T-shirt (M) = $18, no gift note" နဲ့ "1 x Hoodie (XL) = $12, Happy birthday!" ဆိုတဲ့ line နှစ်ကြောင်း ထွက်ပါမယ်။ size: "XXL" လို့ ရေးရင် compile error ဖြစ်ပါမယ်။

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

line.size ရဲ့ type က Size ဖြစ်ပြီး PriceTable ရဲ့ key တွေနဲ့ အတိအကျ တူတာကြောင့် table[line.size] ကို narrowing မလုပ်ဘဲ ရေးလို့ ရပါတယ်။ line.giftNote ?? "no gift note" က null ဖြစ်တဲ့အခါ default ကို ပြန်ပေးပါတယ်။

အဖြေ ကြည့်ရန်
order-lines.ts
type Size = "S" | "M" | "L" | "XL";
type PriceTable = { S: number; M: number; L: number; XL: number };
type OrderLine = {
  item: string;
  size: Size;
  quantity: number;
  giftNote: string | null;
};

const prices: PriceTable = { S: 8, M: 9, L: 10, XL: 12 };

function lineTotal(line: OrderLine, table: PriceTable): number {
  return table[line.size] * line.quantity;
}

function describeLine(line: OrderLine): string {
  const note = line.giftNote ?? "no gift note";
  const total = lineTotal(line, prices);
  return `${line.quantity} x ${line.item} (${line.size}) = $${total}, ${note}`;
}

const order: OrderLine[] = [
  { item: "T-shirt", size: "M", quantity: 2, giftNote: null },
  { item: "Hoodie", size: "XL", quantity: 1, giftNote: "Happy birthday!" },
];
for (const line of order) console.log(describeLine(line));

Quick Quiz 1 / 3

let id: string | number = getId(); ရှိရင် ဘယ် call က narrowing မလုပ်ဘဲ compile ဖြစ်မလဲ?

Quick Quiz 2 / 3

type UserId = string; type OrderId = string; function cancel(id: OrderId) {} ရှိတယ်။ userId: UserId နဲ့ cancel(userId) ကို ခေါ်ရင် ဘာဖြစ်မလဲ?

Quick Quiz 3 / 3

[1, "two", 3] ဆိုတဲ့ array ကို ဘယ် type က လက်ခံမလဲ?

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

  • Union A | B က A ဒါမှမဟုတ် B ဖြစ်တဲ့ value ကို ဖော်ပြပြီး literal union တွေက ပုံသေ option စာရင်းကို model လုပ်ပါတယ်။
  • Narrowing မလုပ်ခင် union value ပေါ်မှာ member တိုင်း share လုပ်တဲ့ operation တွေကိုပဲ သုံးလို့ ရပါတယ်။
  • type Name = ... က union, object shape, function type ဘာမဆို နာမည်ပေးပြီး နေရာတစ်ခုတည်းမှာ ပြင်လို့ရစေပါတယ်။
  • Alias က နာမည်သာ ဖြစ်ပြီး base type တူတဲ့ value တွေကို ခွဲခြားမပေးပါဘူး။

TypeScript Handbook — TypeScript

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

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

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

Union Types & Aliases | Thuta Learning