Mapped Types
7.0.2
ရှိပြီးသား object type ရဲ့ fields တွေကနေ type အသစ် ဆောက်ပါ။ မူရင်း type ပြောင်းရင် လိုက်ပြောင်းသင့်တဲ့ type တွေမှာ သုံးပါ။
Code စမ်းလို့ရတဲ့ သင်ခန်းစာ ဖွင့်ရန်
ဒီစာမျက်နှာမှာ
Type ထဲက Key တစ်ခုချင်းစီကို သုံးပါ
keyof T က T ရဲ့ property names တွေကို ရယူပါတယ်။ Mapped type က key တစ်ခုချင်းကို သုံးပါတယ်။ T[Key] က အဲဒီ property ရဲ့ value type ပါ။ ဒီနမူနာမှာ product update အတွက် field တိုင်းကို optional လုပ်ထားပါတယ်။
type Product = { name: string; quantity: number };
type Patch<T> = {
[Key in keyof T]?: T[Key];
};
const update: Patch<Product> = { quantity: 8 };
Key နဲ့ Modifier ပြောင်းပါ
Key နာမည် ပြောင်းဖို့ as clause သုံးပါ။ Optional ကို ဖယ်ဖို့ -?၊ ရေးလို့ရအောင် readonly ဖယ်ဖို့ -readonly သုံးပါ။ ဒီပြောင်းလဲမှုတွေက compiler စစ်တဲ့ type အပေါ် သက်ရောက်ပါတယ်။
type Getters<T> = {
[Key in Extract<keyof T, string> as `get${Capitalize<Key>}`]: () => T[Key];
};
type ProductGetters = Getters<Product>;
// { getName: () => string; getQuantity: () => number }